DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Coding Topics

article thumbnail
Java Reporting With Jasper Reports - Part 2
Welcome back to Java Reporting series. For those who didn't read the introductory article; have a look before we get started. Today we're going to have a quick tour in JasperReport architecture, development lifecycle, report definition files, and finally we're going to set up our environment and start work in a sample application. Architecture As shown in the above figure JasperReports architecture is based on declarative XML fileswhich by convention have an extension of jrxml that contains the report layout. A lot of third-party design tools were produced to generate your jrxml file in a smooth way (like iReport or JasperAssistant)Design file is supposed to be filled by report's result which is fetched from database, XML files, Java collection, Comma-separated values or Models. Jasper can communicate with those data-sources and more, it can merge any number of data-sources together and manipulates the results of any combinations. This communication goes through JDBC, JNDI, XQuery, EJBQL, Hibernate or existing Oracle PL/SQL. You also can define your own data-source class and pass it to jasper engine directly. After defining your report design layout in jrxml format and determining your data source(s) jasper engine does the rest of work. It compiles your design file and fills it with results fetched from data-source and generates your report to the chosen exporting format (PDF, Excel, HTML, XML, RTF, TXT …, etc.) Report Definition file structure (jrxml): Jasper design file –jrxml- contains the following elements: : the root element.
June 13, 2008
by Hossam Sadik
· 293,262 Views
article thumbnail
.NET Memory control : Use GCHandle to pin down the objects
In the .NET framework memory control is mostly autonomous and is controlled by the CLR. Although in managed languages we do not care much about controlling memory but when we have to interact with other languages we have to be aware of the memory implications. When we create an object in memory there is no guarantee that the object will remain in the same location it was created in. This is because the GC moves memory around by itself when needed to. Variable movement in memory I am sure that everyone reading this have already read about how GC collects memory and generations. As you know that GC allocates memory spaces in bulk. When needed GC collects unused memory and moves it. For example if the object you are using is collected, in order make better allocation GC can move it a different block of memory and free the block you were in. Let think we have a variable called "x" and it allocated in the memory like in the position like shown below. [img_assist|nid=3441|title=|desc=Figure 1: Before GC collection|link=none|align=none|width=240|height=88] In the figure above 1 is the space that are allocated and 0 are the ones that need to garbage collected because there is no reference to it. When GC collects it might decide to move the occupied items to the top block keep the second block empty by compacting. If so our memory could look like this diagram below: [img_assist|nid=3442|title=|desc=Figure 2: After compacting the variable moved to different virtual address|link=none|align=none|width=240|height=88] As you see that GC has moved all items to the first block of memory and the second block is empty which will result in faster memory allocation for new variables and it makes sense to do to so. Our variable x has moved to a different location in memory space which means the address of the memory where the variable is kept has changed. (Please keep in mind that the address space used does not have anything is physical ram as the OS may decide to change the physical address anytime and the address we are referring to is virtual address. Usually GC collect after 256KB of memory has become occupied, depending on the version of GC and OS and the mode it runs. As GC is independent of the thread you are running, it can collect any time. [img_assist|nid=3443|title=|desc=|link=none|align=none|width=418|height=316] If you are doing unmanaged memory operation and you are using the memory address and GC can come in move the memory away as you use the address to do unmanaged operations. Pin down: API Calls to PInvoke So can can this be a problem when we are calling windows APIs? For example, what happens if the window handle (hwnd) that I specified in the pinvoke is moved to a different memory address. The variable is pinned down to memory before the PInvoke call and pinned status is released just after the call. This is done automatically by the CLR. So what would have happened if GC had come in while the unmanaged PInvoke was running? See the figure below: [img_assist|nid=3444|title=|desc=|link=none|align=none|width=391|height=578] As you can see in the figure above that the variable x did not move to another virtual address in memory. This is useful when I need some unmanaged code to access a memory address that is constant. For example lets think of a scenario where I have an integer array which I pass to some unmanaged function and then I change the values of the variable at times and unmanaged function read changed values in the integer array and does some work. In such a scenario I will need the array to remain in one constant space. So I will need GCHandle class to pin it down in memory GCHandle class We find the class in System.Runtime.InteropServices namespace. In order use this class we will need SecurityPermission with Unmanaged code flag most of the time. Each application domain has a for GC handles, with this GCHandle class we can control what items are in that table. The Garbage Collector actually reads this table and abides by it. Each entry in the table points to an object in the managed heap and how GC should treat it. There are four behaviors types as described in the GCHandleType enumeration. They are as follows, 1. Weak 2. WeakTrackResurrection 3. Normal 4. Pinned Weak and WeakTrackResurrection for tracking weak referenced objects (see earlier post WeakReference: GC knows the Best for more on weak references). The Normal type is used to keep an object alive even if there are no reference to it. We are interested in the last type called Pinned. This tells the Garbage Collector to keep this object in memory even if there are no reference to it and never to move this object around in memory. See an example below on how to use the GCHandle class: string name = "My Name"; byte[] nameinbyte = ASCIIEncoding.ASCII.GetBytes(name); // Pin down the byte array GCHandle handle = GCHandle.Alloc(nameinbyte, GCHandleType.Pinned); IntPtr address = handle.AddrOfPinnedObject (); // Do stuff ... with the pinned object address // .... handle.Free(); Things to Remember Please note that too many pinned object will make the GC slowdown. Also only blittable types and arrays of blittable types can be used. If you have written a custom object you can make it blittable by implenting a custom marshaler with the ICustomMarshaler interface.
June 10, 2008
by Shafqat Ahmed
· 41,569 Views
article thumbnail
Hibernate - Tuning Queries Using Paging, Batch Size, and Fetch Joins
This article covers queries - in particular a tuning test case and the relations between simple queries, join fetch queries, paging query results, and batch size. Paging the Query Results I will start with a short introduction about paging in EJB3: To support paging the EJB3 Query interface defines the following two methods: setMaxResults - sets the number of maximum rows to retrieve from the database setFirstResult - sets the first row to retrieve For example if our GUI displays a list of customers and we have 500,000 customers (database rows) in out database we wouldn't like to display all 500,000 records is one view (even if we put performance considerations aside - nobody can do anything with a list of 500,000 rows). The GUI design would usually include paging - we break the list of records to display into logical pages (for example 100 records per page) and the user can navigate between pages (same as Google's results navigator down the search page). When using the paging support it is important to remember that the query has to be sorted otherwise we can't be sure that when fetching the "next page" it will really be the next page (since in the absence of the 'order by' clause form a SQL query the order in which rows are fetch is unpredictable). Here is a sample use, for fetching the first tow pages of 100 rows each: Query q = entityManager.createQuery("select c from Customer c order by c.id"); q.setFirstResult(0).setMaxResults(100); .... next page ... Query q = entityManager.createQuery("select c from Customer c order by c.id"); q.setFirstResult(100).setMaxResults(100); This is a simple API and it's important (for performance) to remember using it when we need to fetch only parts of the results. Test Case Description This test cased is based on a real tuning I did for an application, I just changed the class names to Customer and Order. Let's assume that I have a Customer entity with a set of orders (lazily fetched - but it happens in eager fetch as well) and we need to: Fetch customers and their orders Do it in a "paging mode" - 100 customers per page Tuning Requirement #1 - Fetch Customers and Their Orders There are two possibilities to perform this kind of fetch: Simple select: select c from customer c order by c.id Join fetch: select distinct c from Customer c left outer join fetch c.orders order by c.id The simple select is as simple as it can be, we load a list of customers with a proxy collection in their orders field. The orders collection will be filled with data once I access it (for example c.getOrders().getSize() ). The 'join fetch' means that we want to fetch an association as an integral part of the query execution. The joined fetched entities (in the example above: c.orders) must be part of an association that is referenced by an entity returned from the query (in the example above: c). The 'join fetch' is one of the tools used for improving queries performance (see more in here). The Hibernate core documentations explains that "a 'fetch' join allows associations or collections of values to be initialized along with their parent objects, using a single select" (see here). I have in my database 18,998 customer records, each with few orders. Let's compare execution time for the two queries. My code looks the same for both queries (except of the query itself), I execute the query, then I iterate the results checking the size of of each customer orders collection and print the execution time and number of records fetch (as a sanity for the query syntax): Query q = entityManager.createQuery(queryStr); long a = System.currentTimeMillis(); List l = q.getResultList(); for (Customer c : l) { c.getOrders().size(); } long b = System.currentTimeMillis(); System.out.println("Execution time: " + (b - a)+ "; Number of records fetch: " + l.size() ); And to the numbers (avg. 3 executions): Simple select: 24,984 millis Join fetch: 1,219 millis The join fetch query execution time was 20 times faster(!) than the simple query. The reason is obvious, using the join fetch select I had only one round trip to the database. While using a simple select I had to fetch the customers (1 round trip to the database) and each time I accessed a collection I had another round trip (that's 18,998 additional round trips!). The winner is 'join fetch'. But does it? wait for the next one - the paging... Tuning Requirement #2 - Use Paging The second requirement was to do it in paging - each page will have 100 customers (so we will have 18,900/100+1 pages - the last page has 98 customers). So let's change the code above a little bit: Query q = entityManager.createQuery(queryStr); q.setFirstResult(pageNum*100).setMaxResults(100); long a = System.currentTimeMillis(); List l = q.getResultList(); for (Customer c : l) { c.getOrders().size(); } long b = System.currentTimeMillis(); System.out.println("Execution time: " + (b - a)+ "; Number of records fetch: " + l.size() ); I added the second line which limits the query result to a specific page with up to 100 records per page. And the numbers are (avg. 3 executions): Simple select: 328 millis Join fetch: 1,660 millis The wheel has turned over. Why? First a quote from the EJB3 Persistence specification: "The effect of applying setMaxResults or setFirstResult to a query involving fetch joins over collections is undefined" (section 3.6.1 - Query Interface) We could have stopped here but it is interesting to understand the issue and to see what Hibernate does. To implement the paging features Hibernate delegates the work to the database using its syntax to limit the number of records fetched by the query. Each database has its own proprietary syntax for limiting the number of fetched records, some examples: Postgres uses LIMIT and OFFSET Oracle has rownum MySQL uses its version of LIMIT and OFFSET MSSQL has the TOP keyword in the select and so on The important thing to remember here is meaning of such limit: the database returns a subset of the query result. So if we asked for the first 100 customers which their names contain 'Eyal' the outcome is logically the same as building a table in memory out of all customers that match the criteria and take from there the first 100 rows. And here is the catch: if the query with the limit includes a join clause for a collection than the first 100 row in the "logical table" will not necessarily be the first 100 customers. the outcome of the join might duplicate customers in the "logical tables" but the database doesn't aware or care about that - it performs operations on tables not on objects!. For example think of the extreme case, the customer 'Eyal' has 100 orders. The query will return 100 rows, hibernate will identify that all belong to the same customer and return only one Customer as the query result - this is not what we were asking for. This also works, of course, the other way around. If a customer had more than 100 orders and the result set size was limited to 100 rots the orders collection would not contain all of the customer's orders. To deal with that limitation Hibernate actually doesn't issue an SQL statement with a LIMIT clause. Instead it fetches all of the records and performs the paging in memory. This explains why using the 'join fetch' statement with paging took more than the one without paging - the delta is the in-memory paging done by Hibernate. If you look at Hibernate logs you will find the next warning issued by Hibernate: WARNING: firstResult/maxResults specified with collection fetch; applying in memory! Final Tuning - BatchSize Does it mean that in the case of paging we shouldn't use a join fetch? usually it does (unless your page size is very close to the actual number of records). But even if you use a simple select this is a classic case for using the @BatchSize annotation. If my session/entity manager has 100 customers attached to it than, be default, for each first access to one of the customers' order collection Hibernate will issue a SQL statement to fill that collection. At the end I will execute 100 statements to fetch 100 collections. You can see it in the log: Hibernate: /* select c from Customer c order by c.id */ select customer0_.id as id0_, customer0_.ccNumber as ccNumber0_, customer0_.name as name0_, customer0_.fixedDiscount as fixedDis5_0_, customer0_.DTYPE as DTYPE0_ from CUSTOMERS customer0_ order by customer0_.id limit ? offset ? Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id=? Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id=? Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id=? ............ Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id=? Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id=? Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id=? The @BatchSize annotation can be used to define how many identical associations to populate in a single database query. If the session has 100 customers attached to it and the mapping of the 'orders' collection is annotated with @BatchSize of size n. It means that whenever Hibernate needs to populate a lazy orders collection it checks the session and if it has more customers which their orders collections need to be populated it fetches up to n collections. Example: if we had 100 customers and the batch size was set to 16 when iterating over the customers to get their number of orders hibernate will go to the database only 7 times (6 times to fetch 16 collections and one more time to fetch the 4 remaining collections - see the sample below). If our batch size was set to 50 it would go only twice. @OneToMany(mappedBy="customer",cascade=CascadeType.ALL, fetch=FetchType.LAZY) @BatchSize(size=16) private Set orders = new HashSet(); And in the log: Hibernate: /* select c from Customer c order by c.id */ select customer0_.id as id0_, customer0_.ccNumber as ccNumber0_, customer0_.name as name0_, customer0_.fixedDiscount as fixedDis5_0_, customer0_.DTYPE as DTYPE0_ from CUSTOMERS customer0_ order by customer0_.id limit ? offset ? Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: /* load one-to-many par2.Customer.orders */ select orders0_.customer_id as customer4_1_, orders0_.id as id1_, orders0_.id as id1_0_, orders0_.customer_id as customer4_1_0_, orders0_.description as descript2_1_0_, orders0_.orderId as orderId1_0_ from ORDERS orders0_ where orders0_.customer_id in (?, ?, ?, ?) Back to our test case. In my example setting the batch size to 100 looks like a nice tuning opportunity. And indeed when setting it to 100 the total execution time dropped to 188 millis (that's an 132 (!!!) times faster than worse result we had). The batch size can also be set globally by setting the hibernate.default_batch_fetch_size property for the session factory. From http://www.jroller.com/eyallupu/
June 9, 2008
by Eyal Lupu
· 256,308 Views · 7 Likes
article thumbnail
Java Concurrency: Read / Write Locks
Jakob has done a great series on Java Concurrency - check out the first 14 articles at his blog. Going forward, we're delighted to announce that you'll also be able to follow the series here on JavaLobby. A read / write lock is more sophisticated lock than the Lock implementations shown in the text Locks in Java. Imagine you have an application that reads and writes some resource, but writing it is not done as much as reading it is. Two threads reading the same resource does not cause problems for each other, so multiple threads that want to read the resource are granted access at the same time, overlapping. But, if a single thread wants to write to the resource, no other reads nor writes must be in progress at the same time. To solve this problem of allowing multiple readers but only one writer, you will need a read / write lock. Java 5 comes with read / write lock implementations in the java.util.concurrent package. Even so, it may still be useful to know the theory behind their implementation. Here is a list of the topics covered in this text: Read / Write Lock Java Implementation First let's summarize the conditions for getting read and write access to the resource: Read Access If no threads are writing, and no threads have requested write access. Write Access If no threads are reading or writing. If a thread wants to read the resource, it is okay as long as no threads are writing to it, and no threads have requested write access to the resource. By up-prioritizing write-access requests we assume that write requests are more important than read-requests. Besides, if reads are what happens most often, and we did not up-prioritize writes, starvation could occur. Threads requesting write access would be blocked until all readers had unlocked the ReadWriteLock. If new threads were constantly granted read access the thread waiting for write access would remain blocked indefinately, resulting in starvation. Therefore a thread can only be granted read access if no thread has currently locked the ReadWriteLock for writing, or requested it locked for writing. A thread that wants write access to the resource can be granted so when no threads are reading nor writing to the resource. It doesn't matter how many threads have requested write access or in what sequence, unless you want to guarantee fairness between threads requesting write access. With these simple rules in mind we can implement a ReadWriteLock as shown below: public class ReadWriteLock{ private int readers = 0; private int writers = 0; private int writeRequests = 0; public synchronized void lockRead() throws InterruptedException{ while(writers > 0 || writeRequests > 0){ wait(); } readers++; } public synchronized void unlockRead(){ readers--; notifyAll(); } public synchronized void lockWrite() throws InterruptedException{ writeRequests++; while(readers > 0 || writers > 0){ wait(); } writeRequests--; writers++; } public synchronized void unlockWrite() throws InterruptedException{ writers--; notifyAll(); } } The ReadWriteLock has two lock methods and two unlock methods. One lock and unlock method for read access and one lock and unlock for write access. The rules for read access are implemented in the lockRead() method. All threads get read access unless there is a thread with write access, or one or more threads have requested write access. The rules for write access are implemented in the lockWrite() method. A thread that wants write access starts out by requesting write access (writeRequests++). Then it will check if it can actually get write access. A thread can get write access if there are no threads with read access to the resource, and no threads with write access to the resource. How many threads have requested write access doesn't matter. It is worth noting that both unlockRead() and unlockWrite() calls notifyAll() rather than notify(). To explain why that is, imagine the following situation: Inside the ReadWriteLock there are threads waiting for read access, and threads waiting for write access. If a thread awakened by notify() was a read access thread, it would be put back to waiting because there are threads waiting for write access. However, none of the threads awaiting write access are awakened, so nothing more happens. No threads gain neither read nor write access. By calling noftifyAll() all waiting threads are awakened and check if they can get the desired access. Calling notifyAll() also has another advantage. If multiple threads are waiting for read access and none for write access, and unlockWrite() is called, all threads waiting for read access are granted read access at once - not one by one. Read / Write Lock Reentrance The ReadWriteLock class shown earlier is not reentrant. If a thread that has write access requests it again, it will block because there is already one writer - itself. Furthermore, consider this case: Thread 1 gets read access. Thread 2 requests write access but is blocked because there is one reader. Thread 1 re-requests read access (re-enters the lock), but is blocked because there is a write request In this situation the previous ReadWriteLock would lock up - a situation similar to deadlock. No threads requesting neither read nor write access would be granted so. To make the ReadWriteLock reentrant it is necessary to make a few changes. Reentrance for readers and writers will be dealt with separately. Read Reentrance To make the ReadWriteLock reentrant for readers we will first establish the rules for read reentrance: A thread is granted read reentrance if it can get read access (no writers or write requests), or if it already has read access (regardless of write requests). To determine if a thread has read access already a reference to each thread granted read access is kept in a Map along with how many times it has acquired read lock. When determing if read access can be granted this Map will be checked for a reference to the calling thread. Here is how the lockRead() and unlockRead() methods looks after that change: public class ReadWriteLock{ private Map readingThreads = new HashMap(); private int writers = 0; private int writeRequests = 0; public synchronized void lockRead() throws InterruptedException{ Thread callingThread = Thread.currentThread(); while(! canGrantReadAccess(callingThread)){ wait(); } readingThreads.put(callingThread, (getAccessCount(callingThread) + 1)); } public synchronized void unlockRead(){ Thread callingThread = Thread.currentThread(); int accessCount = getAccessCount(callingThread); if(accessCount == 1){ readingThreads.remove(callingThread); } else { readingThreads.put(callingThread, (accessCount -1)); } notifyAll(); } private boolean canGrantReadAccess(Thread callingThread){ if(writers > 0) return false; if(isReader(callingThread) return true; if(writeRequests > 0) return false; return true; } private int getReadAccessCount(Thread callingThread){ Integer accessCount = readingThreads.get(callingThread); if(accessCount == null) return 0; return accessCount.intValue(); } private boolean isReader(Thread callingThread){ return readers.get(callingThread) != null; } } As you can see read reentrance is only granted if no threads are currently writing to the resource. As you can see, if the calling thread already has read access this takes precedence over any writeRequests. Write Reentrance Write reentrance is granted only if the thread has already write access. Here is how the lockWrite() and unlockWrite() methods look after that little change: public class ReadWriteLock{ private Map<Thread, Integer> readingThreads = new HashMap<Thread, Integer>(); private int writeAccesses = 0; private int writeRequests = 0; private Thread writingThread = null; public synchronized void lockWrite() throws InterruptedException{ writeRequests++; Thread callingThread = Thread.currentThread(); while(! canGrantWriteAccess(callingThread)){ wait(); } writeRequests--; writeAccesses++; writingThread = callingThread; } public synchronized void unlockWrite() throws InterruptedException{ writeAccesses--; if(writeAccesses == 0){ writingThread = null; } notifyAll(); } private boolean canGrantWriteAccess(Thread callingThread){ if(hasReaders()) return false; if(writingThread == null) return true; if(writingThread != callingThread) return false; return true; } private boolean hasReaders(){ return readingThreads.size() > 0; } } Notice how the thread currently holding the write lock is now taken into account when determining if the calling thread can get write access. Read to Write Reentrance Sometimes it is necessary for a thread that have read access to also obtain write access. For this to be allowed the thread must be the only reader. To achieve this the writeLock() method should be changed a bit. Here is what it would look like: public class ReadWriteLock{ private Map readingThreads = new HashMap(); private int writeAccesses = 0; private int writeRequests = 0; private Thread writingThread = null; public synchronized void lockWrite() throws InterruptedException{ writeRequests++; Thread callingThread = Thread.currentThread(); while(! canGrantWriteAccess(callingThread)){ wait(); } writeRequests--; writeAccesses++; writingThread = callingThread; } public synchronized void unlockWrite() throws InterruptedException{ writeAccesses--; if(writeAccesses == 0){ writingThread = null; } notifyAll(); } private boolean canGrantWriteAccess(Thread callingThread){ if(isOnlyReader(callingThread)) return true; if(hasReaders()) return false; if(writingThread == null) return true; if(writingThread != callingThread) return false; return true; } private boolean hasReaders(){ return readingThreads.size() > 0; } private boolean isOnlyReader(Thread thread){ return readers == 1 && readingThreads.get(callingThread) != null; } } Now the ReadWriteLock class is read-to-write access reentrant. Write to Read Reentrance Sometimes a thread that has write access needs read access too. A writer should always be granted read access if requested. If a thread has read access no other threads can have read nor write access, so it is not dangerous. Here is how the canGrantReadAccess() method will look with that change: public class ReadWriteLock{ private boolean canGrantReadAccess(Thread callingThread){ if(isWriter(callingThread)) return true; if(writingThread != null) return false; if(isReader(callingThread) return true; if(writeRequests > 0) return false; return true; } } Fully Reentrant ReadWriteLock Below is the fully reentran ReadWriteLock implementation. I have made a few refactorings to the access conditions to make them easier to read, and thereby easier to convince yourself that they are correct. public class ReadWriteLock{ private Map readingThreads = new HashMap(); private int writeAccesses = 0; private int writeRequests = 0; private Thread writingThread = null; public synchronized void lockRead() throws InterruptedException{ Thread callingThread = Thread.currentThread(); while(! canGrantReadAccess(callingThread)){ wait(); } readingThreads.put(callingThread, (getReadAccessCount(callingThread) + 1)); } private boolean canGrantReadAccess(Thread callingThread){ if( isWriter(callingThread) ) return true; if( hasWriter() ) return false; if( isReader(callingThread) ) return true; if( hasWriteRequests() ) return false; return true; } public synchronized void unlockRead(){ Thread callingThread = Thread.currentThread(); if(!isReader(callingThread)){ throw new IllegalMonitorStateException("Calling Thread does not" + " hold a read lock on this ReadWriteLock"); } int accessCount = getReadAccessCount(callingThread); if(accessCount == 1){ readingThreads.remove(callingThread); } else { readingThreads.put(callingThread, (accessCount -1)); } notifyAll(); } public synchronized void lockWrite() throws InterruptedException{ writeRequests++; Thread callingThread = Thread.currentThread(); while(! canGrantWriteAccess(callingThread)){ wait(); } writeRequests--; writeAccesses++; writingThread = callingThread; } public synchronized void unlockWrite() throws InterruptedException{ if(!isWriter(Thread.currentThread()){ throw new IllegalMonitorStateException("Calling Thread does not" + " hold the write lock on this ReadWriteLock"); } writeAccesses--; if(writeAccesses == 0){ writingThread = null; } notifyAll(); } private boolean canGrantWriteAccess(Thread callingThread){ if(isOnlyReader(callingThread)) return true; if(hasReaders()) return false; if(writingThread == null) return true; if(!isWriter(callingThread)) return false; return true; } private int getReadAccessCount(Thread callingThread){ Integer accessCount = readingThreads.get(callingThread); if(accessCount == null) return 0; return accessCount.intValue(); } private boolean hasReaders(){ return readingThreads.size() > 0; } private boolean isReader(Thread callingThread){ return readingThreads.get(callingThread) != null; } private boolean isOnlyReader(Thread callingThread){ return readingThreads.size() == 1 && readingThreads.get(callingThread) != null; } private boolean hasWriter(){ return writingThread != null; } private boolean isWriter(Thread callingThread){ return writingThread == callingThread; } private boolean hasWriteRequests(){ return this.writeRequests > 0; } } Calling unlock() From a finally-clause When guarding a critical section with a ReadWriteLock, and the critical section may throw exceptions, it is important to call the readUnlock() and writeUnlock() methods from inside a finally-clause. Doing so makes sure that the ReadWriteLock is unlocked so other threads can lock it. Here is an example: lock.lockWrite(); try{ //do critical section code, which may throw exception } finally { lock.unlockWrite(); } This little construct makes sure that the ReadWriteLock is unlocked in case an exception is thrown from the code in the critical section. If unlockWrite() was not called from inside a finally-clause, and an exception was thrown from the critical section, the ReadWriteLock would remain write locked forever, causing all threads calling lockRead() or lockWrite() on that ReadWriteLock instance to halt indefinately. The only thing that could unlock the ReadWriteLockagain would be if the ReadWriteLock is reentrant, and the thread that had it locked when the exception was thrown, later succeeds in locking it, executing the critical section and calling unlockWrite() again afterwards. That would unlock the ReadWriteLock again. But why wait for that to happen, if it happens? Calling unlockWrite() from a finally-clause is a much more robust solution.
June 9, 2008
by Jakob Jenkov
· 79,294 Views
article thumbnail
Easy Unwrapping with IntelliJ IDEA
In complicated code constructs that contain numerous nested statements, you sometimes need to accurately get rid of the enclosing parts. When you try to manually delete such statements, it is too easy to break the syntax of the whole construct. With the new IntelliJ IDEA’s unwrapping feature, this task becomes just a snap. Consider the following example, where a string variable is being analyzed: [img_assist|nid=3370|title=|desc=|link=none|align=left|width=640|height=299] Let’s remove one of the branches. To do that, place the cursor at the branch containing the statement, and press Ctrl+ Shift+Delete. IntelliJ IDEA shows you which results you can obtain: the part that will remain is displayed on the blue background, while the grey background denotes the pieces of code to be deleted: [img_assist|nid=3371|title=|desc=|link=none|align=left|width=640|height=258] After clicking the Remove ‘else…’ option, we get the promised results: [img_assist|nid=3372|title=|desc=|link=none|align=left|width=640|height=226] As you see, all parentheses are properly balanced, and the syntax is correct. However, Java developers are not the only ones who can enjoy this powerful feature. The same “stripping” can be done in XML or HTML code. Consider a situation when you have to clean up some HTML code and get rid of inline styles, for example, remove bold fonts. What will you do in this case – delete an opening tag, then delete the closing tag, with the real possibility to lose something in process. With IntelliJ IDEA, all you have to do is to place the caret somewhere inside the tags, and press Ctrl+Shift+Delete. The unnecessary tags are removed silently. This facility is even more helpful for XML constructs, which can have deep nesting. You can sequentially remove enclosing tags level by level, until getting to the innermost one you want to preserve. Do I need to mention that such unwrapping can be undone? Enjoy!
June 7, 2008
by Irina Megorskaya
· 10,360 Views · 1 Like
article thumbnail
HTML 5 Reverse Ordered Lists
One of the newly introduced features in HTML 5 is the ability to mark up reverse ordered lists. These are the same as ordered lists, but instead of counting up from 1, they instead count down towards 1. This can be used, for example, to count down the top 10 movies, music, or LOLCats, or anything else you want to present as a countdown list. In previous versions of HTML, the only way to achieve this was to place a value attribute on each li element, with successively decreasing values. Top 5 TV Series Friends 24 The Simpsons Stargate Atlantis Stargate SG-1 The problem with that approach is that manually specifying each value can be time consuming to write and maintain, and the value attribute was not allowed in the HTML 4.01 or XHTML 1.0 Strict DOCTYPEs (although HTML 5 fixes that problem and allows the value attribute) The new markup is very simple: just add a reversed attribute to the ol element, and optionally provide a start value. If there’s no start value provided, the browser will count the number of list items, and count down from that number to 1. Greatest Movies Sagas of All Time Police Academy (Series) Harry Potter (Series) Back to the Future (Trilogy) Star Wars (Saga) The Lord of the Rings (Trilogy) Since there are 5 list items in that list, the list will count down from 5 to 1. The reversed attribute is a boolean attribute. In HTML, the value may be omitted, but in XHTML, it needs to be written as: reversed="reversed". The start attribute can be used to specify the starting number for the countdown, or the value attribute can be used on an li element. Subsequent list items will, by default, be numbered with the value of 1 less than the previous item. The following example starts counting down from 100, but omits a few items from the middle of the list and resumes from 3. Top 100 Logical Fallacies Used By Creationists False DichotomyAppeal to RidiculeBegging the Question (Circular Logic)StrawmanBare Assertion FallacyArgumentum ad Ignorantiam This article is released under a MIT license and was posted by Lachlan Hunt
May 24, 2008
by Schalk Neethling
· 31,074 Views
article thumbnail
Spring Batch - Hello World
This is an introductory tutorial to Spring Batch. It does not aim to provide a complete guide to the framework but rather to facilitate the first contact. Spring Batch is quite rich in functionalities, and this is basically how I started learning it. Keep in mind that we will only be scratching the surface. Before we start All the examples will have the lofty task of printing "Hello World!" though in different ways. They were developed with Spring Batch 1.0. I'll provide a Maven 2 project and I'll run the examples with Maven but of course it is not a requirement to work with Spring Batch. Spring Batch in 2 Words Fortunately, Spring Batch model objects have self-explanatory names. Let's try to enumerate the most important and to link them together: A batch Job is composed of one or more Steps. A JobInstance represents a given Job, parametrized with a set of typed properties called JobParameters. Each run of of a JobInstance is a JobExecution. Imagine a job reading entries from a data base and generating an xml representation of it and then doing some clean-up. We have a Job composed of 2 steps: reading/writing and clean-up. If we parametrize this job by the date of the generated data then our Friday the 13th job is a JobInstance. Each time we run this instance (if a failure occurs for instance) is a JobExecution. This model gives a great flexibility regarding how jobs are launched and run. This naturally brings us to launching jobs with their job parameters, which is the responsibility of JobLauncher. Finally, various objects in the framework require a JobRepository to store runtime information related to the batch execution. In fact, Spring Batch domain model is much more elaborate but this will suffice for our purpose. Well, it took more than 2 words and I feel compelled to make a joke about it, but I won't. So let's move to the next section. Common Objects For each job, we will use a separate xml context definition file. However there is a number of common objects that we will need recurrently. I will group them in an applicationContext.xml which will be imported from within job definitions. Let's go through these common objects: JobLauncher JobLaunchers are responsible for starting a Job with a given job parameters. The provided implementation, SimpleJobLauncher, relies on a TaskExecutor to launch the jobs. If no specific TaskExecutor is set then a SyncTaskExecutor is used. JobRepository We will use the SimpleJobRepository implementation which requires a set of execution Daos to store its information. JobInstanceDao, JobExecutionDao, StepExecutionDao These data access objects are used by SimpleJobRepository to store execution related information. Two sets of implementations are provided by Spring Batch: Map based (in-memory) and Jdbc based. In a real application the Jdbc variants are more suitable but we will use the simpler in-memory alternative in this example. Here's our applicationContext.xml: Hello World with Tasklets A tasklet is an object containing any custom logic to be executed as a part of a job. Tasklets are built by implementing the Tasklet interface. Let's implement a simple tasklet that simply prints a message: public class PrintTasklet implements Tasklet{ private String message; public void setMessage(String message) { this.message = message; } public ExitStatus execute() throws Exception { System.out.print(message); return ExitStatus.FINISHED; } } Notice that the execute method returns an ExitStatus to indicate the status of the execution of the tasklet. We will define our first job now in a simpleJob.xml application context. We will use the SimpleJob implementation which executes all of its steps sequentailly. In order to plug a tasklet into a job, we need a TaskletStep. I also added an abstract bean definition for tasklet steps in order to simplify the configuration: ; Running the Job Now we need something to kick-start the execution of our jobs. Spring Batch provides a convenient class to achieve that from the command line: CommandLineJobRunner. In its simplest form this class takes 2 arguments: the xml application context containing the job to launch and the bean id of that job. It naturally requires a JobLauncher to be configured in the application context. Here's how to launch the job with Maven. Of course, it can be run with the java command directly (you need to specify the class path then): mvn exec:java -Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner -Dexec.args="simpleJob.xml simpleJob" Hopefully, your efforts will be rewarded with a "Hello World!" printed on the console. The code source can be downloaded here. What's Next? This is the first part of 3. In the next part we will improve on this example while the third part will be dedicated to item oriented steps and flat files readers and writers. Hope you find it useful.
May 23, 2008
by Tareq Abedrabbo
· 299,468 Views
article thumbnail
Python and the Star Schema
The star schema represents data as a table of facts (measurable values) that are associated with the various dimensions of the fact. Common dimensions include time, geography, organization, product and the like. I'm working with some folks whose facts are a bunch of medical test results, and the dimensions are patient, date, and a facility in which the tests were performed. I got an email with the following situation: "a client who is processing gigs of incoming fact data each day and they use a host of C/C++, Perl, mainframe and other tools for their incoming fact processing and I've seriously considered pushing Python in their organization.". Here are my thoughts on using Python for data warehousing when you've got Gb of data daily. Small Dimensions The pure Python approach only works when your dimension will comfortably fit into memory -- not a terribly big problem with most dimensions. Specifically, it doesn't work well for those dimensions which are so huge that the dimensional model becomes a snowflake instead of a simple star. When dealing with a large number of individuals (public utilities, banks, medical management, etc.) the "customer" (or "patient") dimension gets too big to fit into memory. Special bridge-table techniques must be used. I don't think Python would be perfect for this, since this involves slogging through a lot of data one record at a time. However, Python is considerably faster than PL/SQL. I don't know how it compares with Perl. Any programming language will be faster than any SQL procedure, because there's no RDBMS overhead. For all small dimensions. Load the dimension values from the RDBMS into a dict with a single query. Read all source data records (ideally from a flat file); conform the dimension, tracking changes; write a result record with the dimension FK information to a flat file. Iterate through the dimension dictionary and persist the dimension changes. The details vary with the Slowly Changing Dimension (SCD) rules you're using. The conformance algorithm is is essentially the following: row= Dimension(...) ident= ( row.field, row.field, row.field, ... ) dimension.setdefault( ident, row ) In some cases (like the Django ORM) this is called the get-or-create query. The Dimension Bus For BIG dimensions, I think you still have to implement the "dimension bus" outlined in The Data Warehouse Toolkit. To do this in Python, you should probably design things to look something like the following. For any big dimensions. Use an external sort-merge utility. Seriously. They're way fast for data sets too large to fit into memory. Use CSV format files and the resulting program is very tidy. The outline is as follows: First, sort the source data file into order by the identifying fields of the big dimension (customer number, patient number, whatever). Second, query the big dimension into a data file and sort it into the same order as the source file. (Using the SQL ORDER BY may be slower than an external sort; only measurements can tell which is faster.) Third, do a "match merge" to locate the differences between the dimension and the source. Don't use a utility like diff, it's too slow. This is a simple key matching between two files. The match-merge loop looks something like this. src= sourceFile.next() dim= dimensionFile.next() try: while True: src_key = ( src['field'], src['field'], ... ) dim_key= ( dim['field'], dim['field'], ... ) if src_key < dim_key: # missing some dimension values update_dimension( src ) src= sourceFile.next() elif dim_key < src_key: # extra dimension values dim= dimensionFile.next() else: # src and dim keys match # check non-key attributes for dimension change. src= sourceFile.next() except StopIteration, e: # if source is at end-of-file, that's good, we're done. # if dim is at end of file, all remaining src rows are dimension updates. for src in sourceFile: update_dimension( src ) At the end of this pass, you'll accumulate a file of customer dimension adds and changes, which is then persisted into the actual customer dimension in the database. This pass will also write new source records with the customer FK. You can also handle demographic or bridge tables at this time, too. Fact Loading The first step in DW loading is dimensional conformance. With a little cleverness the above processing can all be done in parallel, hogging a lot of CPU time. To do this in parallel, each conformance algorithm forms part of a large OS-level pipeline. The source file must be reformatted to leave empty columns for each dimension's FK reference. Each conformance process reads in the source file and writes out the same format file with one dimension FK filled in. If all of these conformance algorithms form a simple OS pipe, they all run in parallel. It looks something like this. src2cvs source | conform1 | conform2 | conform3 | load At the end, you use the RDBMS's bulk loader (or write your own in Python, it's easy) to pick the actual fact values and the dimension FK's out of the source records that are fully populated with all dimension FK's and load these into the fact table. I've written conformance processing in Java (which is faster than Python) and had to give up on SQL-based conformance for large dimensions. Instead, we did the above flat-file algorithm to merge large dimensions. The killer isn't the language speed, it's the RDBMS overheads. Once you're out of the database, things blaze. Indeed, products like the syncsort data sort can do portions of the dimension conformance at amazing speeds for large datasets. Hand Wringing "But," the hand-wringers say, "aren't you defeating the value of the RDBMS by working outside it?" The answer is NO. We're not doing incremental, transactional processing here. There aren't multiple update transactions in a warehouse. There are queries and there are bulk loads. Doing the prep-work for a bulk load outside the database is simply more efficient. We don't need locks, rollback segments, memory management, threading, concurrency, ACID rules or anything. We just need to match-merge the large dimension and the incoming facts.
May 20, 2008
by Steven Lott
· 11,320 Views · 1 Like
article thumbnail
Converting a Java Project to a Dynamic Web Project in Eclipse
To convert a Java Project to a Web Project switch to or open the Resource Perspective of the project, in the root of the project. Open the .project file and make sure the builders and natures are present that are needed for a web project. See the example below, the name should be the name of your project, the most important nodes are the nature children in the natures node: testProjectorg.eclipse.jdt.core.javabuilderorg.eclipse.wst.common.project.facet.core.builderorg.eclipse.wst.validation.validationbuilderorg.eclipse.wst.common.project.facet.core.natureorg.eclipse.jdt.core.javanatureorg.eclipse.wst.common.modulecore.ModuleCoreNatureorg.eclipse.jem.workbench.JavaEMFNature Once you’ve updated the .project file you can close the file and right click and choose properties on the project. When the properties window opens click on Project Facets. The Facets grid is probably empty, click the Modify Project button. Check the Dynamic Web Module and Java Facets, choose the Java and Servlet version that applies to your project. Click Next and specify the existing or new location of your src and web content directories. Click Finish. As a final step I would recommend modifying the build path to compile your source directly into your /WEB-INF/classes directory by selecting Java Build Path and modifying the Default output directory. Now you should be able to create a local tomcat server, or if you’ve already created one you should be able to add the project to the server by right clicking the server and choosing Add and Remove Projects. Original article at http://greatwebguy.com/programming/eclipse/converting-a-java-project-to-a-dynamic-web-project-in-eclipse/.
May 6, 2008
by Jason Crow
· 114,803 Views
article thumbnail
Obfuscating a NetBeans Java Application Project
Some time ago I found a couple of posts talking about how to obfuscate a NetBeans RCP module (here and here). Getting some parts of the ant targets presented in the previous post, this one presents a simple target that allows to obfuscate a normal Java library. For this, you need to have installed the obfuscator ProGuard. Take into account I am talking about obfuscating a Java library. This implies the obfuscation is lighter than if you obfuscate a closed application, that is, all public methods and interfaces must maintain its name (if not you can call your library methods anymore). Open your build.xml Java application file and paste this target: Special attention to these couple of lines:
April 30, 2008
by Antonio Santiago
· 46,000 Views · 1 Like
article thumbnail
5 Techniques for Creating Java Web Services From WSDL
WSDL is a version of XML used to better work with web severs. In this post, we'll learn how to better use it alongside the Java language.
April 29, 2008
by Milan Kuchtiak
· 604,604 Views
article thumbnail
Migrate4j - Database Migration Tool for Java
Migrate4j is a migration tool for java, similar to Ruby's db:migrate task. Unlike other Java based migration tools, database schema changes are defined in Java, not SQL. This means your migrations can be applied to different database engines without worrying about whether your DDL statements will still work. Schema changes are defined in Migration classes, which define "up" and "down" methods - "up" is called when a Migration is being applied, while "down" is called when it is being rolled back. A simple Migration, which simply adds a table to a database, is written as: package db.migrations; import static com.eroi.migrate.Define.*; import static com.eroi.migrate.Define.DataTypes.*; import static com.eroi.migrate.Execute.*; import com.eroi.migrate.Migration; public class Migration_1 implements Migration { public void up() { createTable( table("simple_table", column("id", INTEGER, primaryKey(), notnull()), column("desc", VARCHAR, length(50), defaultValue("NA")))); } public void down() { dropTable("simple_table"); } } This Migration can be applied at application startup, from an Ant task (included in migrate4j) or from the command line. Migrate4j will only apply the migration if it has not yet been applied. LIkewise, migrate4j will roll back the migration when instructed, only if the migration has been previously applied. The migrate4j team is happy to announce a new release which adds improved usability (simplified syntax), additional schema changes and support for more database products. While migrate4j does not yet have support for all database products, we are actively seeking developers interested in helping fix this situation. Visit http://migrate4j.sourceforge.net for more information on how migrate4j can simplify synchronizing your databases. To obtain migrate4j, go to http://sourceforge.net/projects/migrate4j and download the latest release. For questions or to help with future development of migrate4j, email us at migrate4j-users AT lists.sourceforge.net (replacing the AT with the "at symbol").
April 28, 2008
by Todd Runstein
· 3,387 Views
article thumbnail
Pathway from ACEGI to Spring Security 2.0
Formerly called ACEGI Security for Spring, the re-branded Spring Security 2.0 has delivered on its promises of making it simpler to use and improving developer productivity. Already considered as the Java platform's most widely used enterprise security framework with over 250,000 downloads from SourceForge, Spring Security 2.0 provides a host of new features. This article outlines how to convert your existing ACEGI based Spring application to use Spring Security 2.0. What is Spring Security 2.0 Spring Security 2.0 has recently been released as a replacement to ACEGI and it provides a host of new security features: Substantially simplified configuration. OpenID integration, single sign on standard. Windows NTLM support, single sign on against Windows corporate networks. Support for JSR 250 ("EJB 3") security annotations. AspectJ pointcut expression language support. Comprehensive support for RESTful web request authorization. Long-requested support for groups, hierarchical roles and a user management API. An improved, database-backed "remember me" implementation. New support for web state and flow transition authorization through the Spring Web Flow 2.0 release. Enhanced WSS (formerly WS-Security) support through the Spring Web Services 1.5 release. A whole lot more... Goal Currently I work on a Spring web application that uses ACEGI to control access to the secure resources. Users are stored in a database and as such we have configured ACEGI to use a JDBC based UserDetails Service. Likewise, all of our web resources are stored in the database and ACEGI is configure to use a custom AbstractFilterInvocationDefinitionSource to check authorization details for each request. With the release of Spring Security 2.0 I would like to see if I can replace ACEGI and keep the current ability to use the database as our source of authentication and authorization instead of the XML configuration files (as most examples demonstrate). Here are the steps that I took... Steps The first (and trickiest) step was to download the new Spring Security 2.0 Framework and make sure that the jar files are deployed to the correct location. (/WEB-INF/lib/) There are 22 jar files that come with the Spring Security 2.0 download. I did not need to use all of them (especially not the *sources packages). For this exercise I only had to include: spring-security-acl-2.0.0.jar spring-security-core-2.0.0.jar spring-security-core-tiger-2.0.0.jar spring-security-taglibs-2.0.0.jar Configure a DelegatingFilterProxy in the web.xml file. springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain /* Configuration of Spring Security 2.0 is far more concise than ACEGI, so instead of changing my current ACEGI based configuration file, I found it easier to start from a empty file. If you do want to change your existing configuration file, I am sure that you will be deleting more lines than adding. The first part of the configuration is to specifiy the details for the secure resource filter, this is to allow secure resources to be read from the database and not from the actual configuration file. This is an example of what you will see in most of the examples: Replace this with: The main part of this piece of configuration is the secureResourceFilter, this is a class that implements FilterInvocationDefinitionSource and is called when Spring Security needs to check the Authorities for a requested page. Here is the code for MySecureResourceFilter: package org.security.SecureFilter; import java.util.Collection; import java.util.List; import org.springframework.security.ConfigAttributeDefinition; import org.springframework.security.ConfigAttributeEditor; import org.springframework.security.intercept.web.FilterInvocation; import org.springframework.security.intercept.web.FilterInvocationDefinitionSource; public class MySecureResourceFilter implements FilterInvocationDefinitionSource { public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException { FilterInvocation filterInvocation = (FilterInvocation) filter; String url = filterInvocation.getRequestUrl(); // create a resource object that represents this Url object Resource resource = new Resource(url); if (resource == null) return null; else{ ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor(); // get the Roles that can access this Url List roles = resource.getRoles(); StringBuffer rolesList = new StringBuffer(); for (Role role : roles){ rolesList.append(role.getName()); rolesList.append(","); } // don't want to end with a "," so remove the last "," if (rolesList.length() > 0) rolesList.replace(rolesList.length()-1, rolesList.length()+1, ""); configAttrEditor.setAsText(rolesList.toString()); return (ConfigAttributeDefinition) configAttrEditor.getValue(); } } public Collection getConfigAttributeDefinitions() { return null; } public boolean supports(Class arg0) { return true; } } This getAttributes() method above essentially returns the name of Authorities (which I call Roles) that are allowed access to the current Url. OK, so now we have setup the database based resources and now the next step is to get Spring Security to read the user details from the database. The examples that come with Spring Security 2.0 shows you how to keep a list of users and authorities in the configuration file like this: You could replace these examples with this configuration so that you can read the user details straight from the database like this: While this is a very fast and easy way to configure database based security it does mean that you have to conform to a default databases schema. By default, the requires the following tables: user, authorities, groups, group_members and group_authorities. In my case this was not going to work as my security schema it not the same as what the requires, so I was forced to change the : By adding the users-by-username-query and authorities-by-username-query properties you are able to override the default SQL statements with your own. As in ACEGI security you must make sure that the columns that your SQL statement returns is the same as what Spring Security expects. There is a another property group-authorities-by-username-query which I am not using and have therefore left it out of this example, but it works in exactly the same manner as the other two SQL statements. This feature of the has only been included in the past month or so and was not available in the pre-release versions of Spring Security. Luckily it has been added as it does make life a lot easier. You can read about this here and here. The dataSource bean instructs which database to connect to, it is not included in my configuration file as it's not specific to security. Here is an example of a dataSource bean for those who are not sure: And that is all for the configuration of Spring Security. My last task was to change my current logon screen. In ACEGI you could create your own logon by making sure that you POSTED the correctly named HTML input elements to the correct URL. While you can still do this in Spring Security 2.0, some of the names have changed. You can still call your username field j_username and your password field j_password as before. However you must set the action property of your to point to j_spring_security_check and not j_acegi_security_check. Logout Conclusion This short guide on how to configure Spring Security 2.0 with access to resources stored in a database does not come close to illustrating the host of new features that are available in Spring Security 2.0, however I think that it does show some of the most commonly used abilities of the framework and I hope that you will find it useful. One of the benefits of Spring Security 2.0 over ACEGI is the ability to write more consice configuration files, this is clearly shown when I compare my old ACEGI configration (172 lines) file to my new one (42 lines). Here is my complete securityContext.xml file: As I said in step 1, downloading Spring Security was the trickiest step of all. From there on it was plain sailing...
April 22, 2008
by Chris Baker
· 117,867 Views
article thumbnail
Image Cross Fade Transition with jQuery
a frequent query and request i receive, and have had as a developer myself is: “how can i fade one image into another?”. in particular, nathan wrigley of pictureandword.com , needed a method which would fade one image into another on a mouse roll over event, and then slowly fade back once the mouse has moved of the image. image rollovers were the staple javascript nugget of the 90s, and for a lot of javascript developers i know, one of the starting points that led to their passion for the javascript language. today, rollovers are a no-brainer, whether with css or the simplest of javascript: $(function () { $('img.swap').hover(function () { this.src="images/sad.jpg"; }, function () { this.src="images/happy.jpg"; });}); today’s challenge is the rollover transition! watch the complete screencast ( alternative flash version ) (quicktime version is approx. 20mb, flash version is streaming) how to approach the problem there are a few different ways in which this problem can be solved (and i’d love to hear alternative methods via the ). here are the different approaches i’m going to go through: two image single image pure css the key to all of these techniques is how the rendered markup (i.e. what the browser finally sees) is arranged: all of which are very similar. essentially, the end image for the transition must sit absolute ly in the same position as the starting image. it’s also worth keeping in mind that the images we fade between should be the same size (height & width-wise). note: all three of these techniques have a caveat: styling the start or end image may cause the effect to break. i would recommend wrapping the image in a div or span and styling that element, as it will require less changes to the javascript. either way: it is always best to test in the targeted browsers. two image technique i should start by crediting karl swedberg who runs learning jquery . he solved nathan’s transition problem using the following technique. karl’s method starts with the two images in the markup: both the start and end images. they are contained in a div and the end image is contained in a further div with absolute positioning. it is important to note that this technique works best for absolutely position images. changing the div.fade to position: relative means the div element remains as a block element, and div will stretch the width of it’s container element (defaulting to 100%). view the working example and the source html css obviously if i had more than one fading image, i would use an id or alternative class to position the top and left css properties. .fade { position: absolute; top: 100px left: 100px } .fade div { position: absolute; top: 0; left: 0; display: none; } jquery // when the dom is ready: $(document).ready(function () { // find the div.fade elements and hook the hover event $('div.fade').hover(function() { // on hovering over, find the element we want to fade *up* var fade = $('> div', this); // if the element is currently being animated (to a fadeout)... if (fade.is(':animated')) { // ...take it's current opacity back up to 1 fade.stop().fadeto(250, 1); } else { // fade in quickly fade.fadein(250); } }, function () { // on hovering out, fade the element out var fade = $('> div', this); if (fade.is(':animated')) { fade.stop().fadeto(3000, 0); } else { // fade away slowly fade.fadeout(3000); } }); }); single image technique this takes the two image technique further. i like the idea that we should let javascript add the sugar to the markup - in that we should really only want an image tag, and using some method, know which image we want to fade to. this technique allows us to insert the image in the markup as we would if there were no transition effect, and the image can be inline, rather being positioned absolutely. we are going to use the background-image css property to specify the target image to fade to. view the working example and the source html css other than the inline background image - none is required. you can also apply the background-image using classes if you like. if we wanted to absolutely position the image, or float: right for instance, the best way to do this (if we want to keep the transition), would be to wrap it in a div and style that element. jquery using jquery, we execute the following tasks: wrap the image in a span insert a new image, whose source is the background-image of our start image position the new image so that sits directly behind the starting image bind the hover event to start the effect // create our transition as a plugin $.fn.crossfade = function () { return this.each(function () { // cache the copy of jquery(this) - the start image var $$ = $(this); // get the target from the backgroundimage + regexp var target = $$.css('backgroundimage').replace(/^url|[\(\)]/g, '')); // nice long chain: wrap img element in span $$.wrap('') // change selector to parent - i.e. newly created span .parent() // prepend a new image inside the span .prepend('') // change the selector to the newly created image .find(':first-child') // set the image to the target .attr('src', target); // position the original image $$.css({ 'position' : 'absolute', 'left' : 0, // this.offsettop aligns the image correctly inside the span 'top' : this.offsettop }); // note: the above css change requires different handling for opera and safari, // see the full plugin for this. // similar effect as single image technique, except using .animate // which will handle the fading up from the right opacity for us $$.hover(function () { $$.stop().animate({ opacity: 0 }, 250); }, function () { $$.stop().animate({ opacity: 1 }, 3000); }); }); }; // not only when the dom is ready, but when the images have finished loading, // important, but subtle difference to $(document).ready(); $(window).bind('load', function () { // run the cross fade plugin against selector $('img.fade').crossfade(); }); pure css technique if i’m honest, this final technique is a bit cheeky - but still valid. it uses css animations currently only available in safari 3 (and webkit). however, this is a great example of how to the leverage css using an iphone, in place javascript. the html is the same rendered html from the single image technique - but it requires zero javascript. html css although this is only supported in safari 3, the roll over still works in firefox (and could work in ie7 - though not ie6 because :hover only works on anchors) - because it’s changing the image’s opacity on :hover . img.fade { opacity: 1; -webkit-transition: opacity 1s linear; } img.fade:hover { opacity: 0; } taking it further i’ve taken the single image technique further in to a complete plugin. it’s designed to allows us to pass options to control the type of bind, delays, callbacks and tests before running the animation. download the full plugin you can see the plugin in action in this simple memory game i put together quickly. it pulls the latest photos from flickr , shuffles them, and then sets your memory skills to work. it’s obviously just a quick prototype - and i’m not sure what happens when you go beyond level 5! enjoy.
April 21, 2008
by $$anonymous$$
· 160,795 Views
article thumbnail
Intro to Design Patterns: Factory Method Pattern
Last week, in part 1, Andre Mare introduced us to the Builder pattern. Today he continues his series on the "Gang of Four" design patterns. -- Geertjan Wielenga, JavaLobby Zone Leader Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. - Gof Type Class Creational Solution The Factory Method Pattern is a well known Creational Pattern that creates an abstraction through which one of several classes is returned. The pattern enables us to encapsulate the instantiation of concrete types. The pattern is classified as a Class Creational Pattern which means the pattern makes use of inheritance to decide what object to instantiate. The Factory Method Pattern consists of a Product, ConcreteProduct, Creator, ConcreteCreator and Client. The Product defines the type or interface for the concrete objects that are created by the Factory Method. The ConcreteProduct provides the implementation of the different Product types created by the Factory Method. The ConcreteProduct is instantiated by the factory method of the different ConcreteCreator objects. The Creator class specify the creator method or factory method that returns objects of type Product. The ConcreteCreator provides the concrete factory methods. These methods override the factory method in the Creator class to return the ConcreteProduct instance. The Client object is decoupled from the ConcreteProduct objects, but uses the factory method to return the appropriate ConcreteProduct through the Product type. The pattern makes use of polymorphism to decouple the client from the class created by the Factory Method. The Factory Method returns an instance of a class (ConcreteProduct) that is defined through an interface or abstract parent (Product) class. The method where the class is created returns the object through its interface or abstract parent class, so that the client is decoupled from the actual ConcreteProduct class. All the returned classes through the factory methods have the same type (interface) or abstract parent class. Structure Java Sample Code Download : Bank Account System The following example will illustrates the use of the Factory Method pattern. The Bank Account System example illustrates the creation of different bank accounts for different banks. The first diagram illustrates the different bank account types that are available. Product & ConcreteProducts The Bank Account System contains an abstract type for all the bank accounts available called the BacnkAccountProduct. The other classes are ConcreteProduct classes that is created by the Factory Method, depending on the type and the ConcreteCreator class. Creator & ConcreteCreator The BankAccountCreator or Creator class defines the factory method as abstract so that the implementation is delegated to the subclasses. The factory method is defined as follows: protected abstract BankAccountProduct createBankAccount(String accountType); This factory method is then implemented in all the different subclasses of the BankAccountCreator class. Each different ConcreteCreator knows how to instantiate the different ConcreteProduct classes. Factory Method Class Diagram The class diagram below show the dependencies between the different classes as used in the Bank Account System example. The BankSystemClient class has a gets a reference to an object of type BankAccountProduct. The client does not know what the implementing class is, but rather works through the abstract BankAccountProduct class. Sequence Diagram Sequence Diagram by "Yanic Inghelbrecht" with Trace Modeler References Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley, 1995
April 21, 2008
by Andre Mare
· 27,041 Views
article thumbnail
Intro to Design Patterns: Builder Pattern
Either because you're new to them, or as a refresher, here is the start of a series on the "Gang of Four" design patterns. Andre Mare, the author of the Java Design Concepts blog, is a J2EE Specialist and has more than seven years experience in development and design of enterprise systems. Here he starts a series of articles that aim to introduce you to the "Gang of Four" design patterns. -- Geertjan Wielenga, JavaLobby Zone Leader Intent of the Pattern The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. - Gof Type Object Creational Solution The Builder Pattern simplifies the construction of complex objects by only specifying the type and content that the object requires. The construction process of the complex object will therefore allow for different representations of the complex object to be created by the different builders. Each of the concrete builder objects will construct a different representation of the complex object. The Builder Pattern consists of a Builder, ConcreteBuilder, Director and Product. The Director object is responsible for the construction process of the complex object but delegates the actual creation and assembly to the Builder interface. The Builder object specifies the interface for creating parts of the complex object. The Product represents the complex object that is created by the ConcreteBuilder objects. The Product consists of multiple parts that are created separately by the ConcreteBuilder objects. The ConcreteBuilder objects create and assemble the parts that make up the Product through the Builder interface. A client object creates an instance of the Director object and passes it the appropriate Builder object. The Director object invokes the methods on the Builder object to create and initialize specific parts of the Product object. The Builder receives content from the Director object and adds these to the Product object. The Client object has a reference to the Builder object and retrieves the created Product object from it. Structure The construction of the Complex object (Product) is hidden by the Builder objects from the Client and Director objects. To change the internal representation of the complex object, a new concrete builder object is defined and used by the client through the Director object. Unlike other creational patterns, the Builder Pattern creates the complex object is sections through the Director and Builder objects. The Builder object may need access to information that was used in previous construction steps. This means that even thought the parts of a Product object is created in individual sections; they may interact with other sections to create the complex product object. The complex Product objects do not usually have a shared abstract parent object, as their representation differ and a shared parent class or interface might not be possible. As the client object specify the Builder object, it should have the knowledge how to handle the product object that is created by the Builder object. Java Sample Code The example for the Builder Pattern is a meal that can be purchased at many fast food franchises. The complex Product is a combo meal that consists of a burger, beverage and a side order. The Builder objects are the different assistants at the till that knows how to create the combo meal for the client. The Director object is the instructions the client gives the assistant on how the specific order should be created. Example Combo Meal: Download Combo Meal Example ComboMealClient.java The ComboMealClient class makes use of the ComboMealDirector and the ComboMeal1ConcreteBuilder class to create a complex object called ComboMealProduct. Code: ComboMeal1ConcreteBuilder concreteBuilder = new ComboMeal1ConcreteBuilder(); ComboMealDirector mealDirector = new ComboMealDirector(concreteBuilder); ComboMealProduct comboMealProduct = null; mealDirector.constructComboMeal(SuperSize.HUGE); comboMealProduct = concreteBuilder.getComboMealProduct(); ComboMealDirector.java The ComboMealDirector class invokes the appropriate methods on the ConcreteBuilder (ComboMeal1ConcreteBuilder) to create a complex product ComboMealProduct. Code: public void constructComboMeal(SuperSize _mealSize) { comboMealBuilder.buildBurgerPart(); comboMealBuilder.buildSideOrderPart(_mealSize); comboMealBuilder.buildBeveragePart(_mealSize); } // method constructComboMeal ComboMealProduct.java The ComboMealProduct class is the complex object whose individual parts is created by the different Builder objects. ComboMealBuilder.java The ComboMealBuilder class contains the interface that is used by the ComboMealDirector to create the complex object. ComboMeal1ConcreteBuilder.java The ComboMeal1ConcreteBuilder class contains implementation that is used by the ComboMealDirector to create the complex object. Class Diagram Example Sequence Diagram Sequence Diagram by "Yanic Inghelbrecht" with Trace Modeler References Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley, 1995
April 15, 2008
by Andre Mare
· 76,353 Views
article thumbnail
Quick Start: Creating Language Tools In NetBeans IDE
NetBeans IDE is one of the main free Java editors in the market. In fact, it can be used to program in many other computer languages, like C/C++, Ajax, Javascript. NetBeans IDE can be extended by adding modules that add new features. So... you can have a programming editor customized to your needs. This tutorial can be of interest for all those who want to create a module that adds support for a new language inside NetBeans IDE. Original article: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html (the original article has coloring that makes reading easier. If you have some dificulty reading it here, you can go there). The process of creating the first of the modules that compose my X3DV Module Suite was similar to the one described here. We will learn how to make a module that has these features: Syntax highlighting that is specific for the language we will define. Brace completion and auto-indentation. Icons for the new files of that language. To be able to create new files written in our new language. Template for the new files written in that language. Just download the last version of NetBeans IDE (download NetBeans IDE 6.1 Beta). Then, follow all the steps described here. This tutorial is valid for the 6.1 version of NetBeans IDE, which has many improvements that make module building easier. This tutorial takes a fictional language called Foo Language as a sample. I suggest to follow the tutorial as it is, and later, adapt it to your needs. This is not a highly technical tutorial, but a quickstart guide that can be very easy for newcomers. First Steps With Your Module Create a new NetBeans project: Choose NetBeans Modules in Categories and Module in Projects: Fill in your project Name, locate the directory where its project folder will be placed, and mark it as a Standalone Module. Fill the info for your module. You just have to fill the two first text boxes: change the Code Name Base to what is appropriate for your module and choose a Display Name. The project will be created. Now we will add the basic: support files for the new file type. New File Type Support Over the project name, right click and select New/File Type: In the dialog that appears, you must enter some data so the NetbBeans IDE recognizes the new file type. In MIME Type you must enter text/x- usually followed by the main extension of the file type. Why does it say text/x-? As you may note, what you enter is not the true MIME type. For the IDE, all the extensions we create are text files. In Extension(s) you must enter them separated with spaces. In our example, there's only one extensions for Foo Files: .foo In Class Name Prefix, you enter the name of the file type, so all classes generated by the IDE for this module will start with it. In Icon, you must locate in your hard drive a gif icon of 16x16 pixels. In our example, it's this: Although in some tutorials they say that jpg and png images can also be used, I found that sometimes they're not displayed. So I recommend using gif images, as they are less error-prone. The IDE will copy your icon to the project directory. At this point, a bunch of files will be created by NetBeans IDE and opened in the code editor. Close them all, you don't need to edit them. Now our module is ready to recognize and create the new file types. But we want the new files to have a default content. So we will edit the generated template. Locate the file named: Edit it and write the content that you want to be the default when you create a new file. Locate the XML Layer in the module. The XML Layer file is the soul of our module. It controls most of the things that a module can do. Locate these lines: The next step is to create a description of the new supported file type that will be displayed when you want to create it, in the New File Wizard. This description will be stored in a file called "Description.html" (strange... uh?). Add this line after the one highlighted in blue, modifying it to your project url: This line we added describes where the Description of the new file is. Right click over your project and select New/Other. Select Other/HTML file. Name the file "Description", and leave the rest as it is. Replace all the contents of the generated file with this: Creates a foo file that is useful for nothing at all. This is what we will see as a result of these steps once the module is finished and we want to create a Foo file. Create the Language Support Now that we have the new files recognized, we will add syntax coloring and other features to our language module. To be able to support language features, we must do the following: right click over your project and choose "Properties". The properties of your module will be displayed. Click over libraries (on the left) and then the "Add..." button. In the list, search for the entry called "Generic Languages Framework", and add it. Now, right click over your project and select New/Other. In Categories, select "Module Development", and on the right, select "Language Support". Then enter the MIME Type and Extensions as we did in the first section of our tutorial. You will see that the XML Layer has changed and now has more things added. Between them, there's a new file that describes our language. That file is called "language.nbs". As the XML Layer has been modified, the icon of our files may have disappeared, so we need to add something to the XML Layer file to recover it. Close all the opened files. Locate the file called XML Layer, and open it. Locate the line highlighted in blue in this image, that says And replace that entire line with: Editing The Language File The default language.nbs file is filled with contents that may be a good start point for a scripting language. For declarative languages like VRML or X3D, or markup languages like HTML or similar, these contents are not useful. In our example of the Foo Language, we will use a very simple language definition. This way you will understand the basics of defining languages. So delete all the contents of the file language.nbs, and replace them with this: # To change this template, choose Tools | Templates # and open the template in the editor. # definition of tokens TOKEN:header:( "# foo language v1.0" ) TOKEN:line_comment: ( "#"[^ "\n" "\r"]* | "//"[^ "\n" "\r"]* ) TOKEN:keyword:( "foo_function" | "foo_command" ) TOKEN:field:( "foo_value" ) # all that follows is useful for mostly all languages TOKEN:identifier: ( ["a"-"z" "A"-"Z"] ["a"-"z" "A"-"Z" "0"-"9" "_"]* ) TOKEN:number: (["0"-"9"]*) TOKEN:operator: ( ":" | "*" | "?" | "+" | "-" | "[" | "]" | "<" | ">" | "^" | "|" | "{" | "}" | "(" | ")" | "," | "=" | ";" | "." | "$" ) TOKEN:string:( "\"" ( [^ "\"" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\"" ) TOKEN:string:( "\'" ( [^ "\'" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\'" ) TOKEN:whitespace:( [" " "\t" "\n" "\r"]+ ) # colors COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } COLOR:keyword:{ foreground_color:"red"; font_type:"bold"; } COLOR:field:{ foreground_color:"#25A613"; font_type:"bold"; } # parser should ignore whitespaces SKIP:whitespace # brace completion COMPLETE "{:}" COMPLETE "(:)" COMPLETE "\":\"" COMPLETE "\':\'" # brace matching BRACE "{:}" BRACE "(:)" # indentation support INDENT "{:}" INDENT "(:)" Now, create a Foo file, using a plain text editor, and save it with the extension .foo These will be its contents: # foo language v1.0 # comment // another comment foo_function { foo_command ( foo_value 1 0 1 ); } Now let's see the language.nbs file and understand the basic parts. TOKEN:header:( "# foo language v1.0" ) TOKEN:keyword:( "foo_function" | "foo_command" ) The Tokens are the words that are part of your language, and you want them colored. They define types of words that have something in common in your language. You group them into a category, that is a token. The words are between double quotes, and separated by a | sign. COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } This defines the colors used for each token. You can specify more properties for colors, but these are the basic ones. All these properties are very easy to understand by their own names, as you see. The colors can be specified by their names (although it recognizes only a few) or by its number. # brace completion COMPLETE "{:}" What these lines do is that when you type a { sign, the editor automatically will type } after your caret, speeding your work and making it less error-prone. # brace matching BRACE "{:}" # indentation support INDENT "{:}" This sentences make that when you place the caret over a brace, the matching brace will be highlighted, and that lines after those signs will be indented. Final Note Now you know all that is needed to create the basic support for a new file type and language syntax highlighting. You can add anything you like to your module, that you think is important for you and that could make your work easier. There's much more than can be done with NetBeans IDE. I invite just to test it, join its huge community of users, and experience it by yourself. -Jordi R. Cardona- X3D/VRML Worldbuilder Java Programmer X3DV Module Suite Developer. Hiperia3D News © 2008 by Jordi R. Cardona. The images and text of this post were added by the author to dzone. The author has granted dzone.com with exclusivity to use these images and text for the only purpose to spread this article. If you want to promote this tutorial, you can link to the original one at: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html
April 14, 2008
by Jordi R Cardona
· 40,066 Views
article thumbnail
1st Binary Release of Java Music Composer
Today marks the availability of the first binary release of the open source JFugue Music NotePad. The core basic functionality of the tool is available and ready to be tried out. After downloading and unzipping the archive, you need to specify the location of the JDK (JDK 5 or above, so Mac users are welcome too), in etc/mnotepad.conf, which is in the unzipped archive's main directory. The binary can be downloaded here: mnotepad_9April2008.zip Once you have done so, you can launch it, which should result in the following main window at start up: Here it is on the Mac: Then choose File | New, to define a new composition: Click Finish and you can begin composing music. To do so, choose notes from the toolbar and point/click to add them to the composition. Currently you can't add notes between existing notes. However, select one/more notes with your mouse, the notes turn red to show they are selected, and then use up/down to move notes up the scale and left/right to decrease/increase their length. While doing this part of the work, compositions typically look something like this: You can change instruments by right-clicking one in the Instruments window and choosing "Select". Finally, click Play to play the music or Save to save it. Compositions are saved to disk in midi format, the status bar shows where they are saved to, in the installation directory. Architecture. Instead of dealing directly with the Midi API, the JFugue API is used instead. The JFugue API provides an extremely transparent, simple, yet surprisngly powerful layer of functionality on top of the complexities of typical Midi programming. The user interface is pure Swing on top of the NetBeans Platform, therefore the application has a very mature window system (max/minimize, dock/undock) and is pluggable out of the box, among other features. User Comments. One of the user comments thus far: "It's definitely very cool! And as promised, you already got a whole bunch of subtle features for free from the NetBeans Platform (windowing, favorites, etc). :-D It already looks more stable and trustworthy than any other app with the same amount of work invested, just because of the solid and consistent windowing system." Known Issues. Amongst others, the following: several usability issues, such as that it isn't easy to know/see from the ui that notes can be changed by selecting them and moving up/down/left/right. Should be able to specify where saved midi file should be saved to. Some users report not being able to change instruments. Keyboard window currently unused. Playing of tune blocks the ui. Feedback Welcome. The JFugue Music NotePad is an open source project at https://nbjfuguesupport.dev.java.net/. You are welcome to join, especially if you are able to offer time/insight to add missing features. Especially programmers who are also musicians are welcome. For example, this application could do with a metronome, which could be provided by a separate plugin...
April 9, 2008
by Geertjan Wielenga
· 12,796 Views
article thumbnail
Eclipse Adapters - A Hands-On, Hand-Holding Explanation
When programming Eclipse plug-ins, you quickly come face to face with Eclipse adapters. If you are not familiar with the adapter pattern, adapters can be confusing. Eclipse adapters are actually very simple, and I hope to make them even simpler with this article. Adapters work on a simple premise: Given some adaptable object A, get me the relevant object of type B for it. The Eclipse adapter interface is shown in Listing 1. The interface returns an object which is an instance of the given class associated with the object or it returns null if no such associated object can be found. package org.eclipse.core.runtime; public interface IAdaptable { public Object getAdapter(Class adapter); } Listing 1: The Eclipse Adapter Interface For instance, if I wanted to go from apples to oranges then I would do something like Listing 2. In this example, IApple extends the IAdaptable interface. IApple macintosh = new Macintosh(); IOrange orange = (IOrange) macintosh.getAdapter(IOrange.class); if (orange==null) log("No orange"); else log("Created a "+ orange.getClass().getCanonicalName()); Listing 2: Adapting from Apples to Oranges One of the primary uses of adapters is to separate model code from view code, as in a view-model-controller or view model-presenter pattern. We would not want to put presentation information like icons in our apple model. We would another class to handle how to present it. We could do this with adapters as shown in Listing 3. IApple apple = new Macintosh(); ILableProvider label = (ILabelProvider)apple.getAdapter(ILabelProvider.class); String text = label.getText(apple); Listing 3: Using Adapters to seperate model from view. Adapters allow us to transform objects into other purposes that the objects did not need to anticipate. For instance, the apple objects in the Listing 3 do not need to know anything about the label provider. We can implement the getAdapter() method manually for each apple object, but that would defeat the purpose. Instead, we should defer the adaptation to the platform as shown in Listing 4. public abstract class Fruit implements IAdaptable{ public Object getAdapter(Class adapter){ return Platform.getAdapterManager().getAdapter(this, adapter); } } Listing 4: Adapting through the platform Adapter Factories To enable the platform to manage the adaptations, you need to register one or more adapter factories with the platform. The registration can be a bit confusing, so I am going to be very specific. package com.jeffricker.fruit; import org.eclipse.core.runtime.IAdapterFactory; import com.jeffricker.fruit.apples.IApple; import com.jeffricker.fruit.apples.Macintosh; import com.jeffricker.fruit.oranges.IOrange; import com.jeffricker.fruit.oranges.Mandarin; /** * Converts apples to oranges * @author Ricker */ public class OrangeAdapterFactory implements IAdapterFactory { public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IOrange.class) { if (adaptableObject instanceof Macintosh) { return new Mandarin(); } } return null; } public Class[] getAdapterList() { return new Class[]{ IOrange.class }; } } Listing 5: Apples to Oranges adapter factory Listing 5 shows an adapter factory that converts apples to oranges. The factory enables the behavior shown earlier in Listing 2. We will detail its behavior. The adaptableObject is the object that we are starting with, the apple. The adaptableObject is always an object instance. The adapterType is the object to which we are adapting, the orange. The adapterType is always a class type, not an object instance The adapterType is always a class type, not an object instance. The adapter list is the list of class types to which this factory can adapt objects. In this case, it is only oranges. We must register the adapter factory with the Eclipse platform in order for it to be useful. Listing 6 shows the registration entry from the plug-in manifest file. The extension point is org.eclipse.core.runtime.adapters. This is where I usually mess up, so pay attention. The adaptableType is what we are adapting from. In this case, it is apples. The adapter is what we are adapting to. In this case, it is oranges. Listing 6: Registering the adapter factory There can be multiple adapter entries for the factory. The adapters listed in the extension point should be the same as those provided by the getAdapterList() method in the adapter factory. If we look at the listings together and trace through the logic, the adapters start to make sense. We create an instance of the Macintosh object. IApple macintosh = new Macintosh(); We request the Macintosh to adapt to an IOrange IOrange orange = (IOrange) macintosh.getAdapter(IOrange.class); The Macintosh object forwards the request to the platform public Object getAdapter(Class adapter){ return Platform.getAdapterManager().getAdapter(this, adapter); } The platform finds the appropriate adapter factory through the registry. The platform calls the factory method, passing it an instance of the Macintosh object and the IOrange class type. The adapter factory is creates an instance of the Mandarin object public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IOrange.class) { if (adaptableObject instanceof Macintosh) { return new Mandarin(); } } return null; } The confusion arises for me with the adaptableType parameter in the extension point. We do not have that specified in the adapter factory interface. It is buried within the logic of the factory’s getAdapter() method. Its presence in the registry makes sense when you think about it. We ask the platform to find an adapter for a Macintosh object. The factories must somehow be associated to the class hierarchy of Macintosh. In our case the factory is registered with IApples. Figure 1 shows the relation between declarations in the extension point registry and the adapter factory class. [img_assist|nid=2268|title=Figure 1: Relation between factory and extension point|desc=|link=none|align=undefined|width=545|height=437] Presentation provider example Adapting apples to oranges is a silly example of course, but I could extend the example to something more relevant. In Listing 3 I showed the adaptation of an apple object to a ILabelProvider, an interface used by JFace widgets for presentation. The factory for this effort is shown in Listing 7. The registration is shown in Listing 8 and sketch of the providers is shown in Listing 9. If you look at the provider classes generated by the Eclipse Modeling Framework (EMF), you will see the concept of this example taken its logical conclusion. package com.jeffricker.fruit.provider; import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import com.jeffricker.fruit.apples.IApple; import com.jeffricker.fruit.oranges.IOrange; public class FruitProviderAdapterFactory implements IAdapterFactory { private AppleProvider appleProvider; private OrangeProvider orangeProvider; /** The supported types that we can adapt to */ private static final Class[] TYPES = { FruitProvider.class, ILabelProvider.class, IContentProvider.class }; public Object getAdapter(Object adaptableObject, Class adapterType) { if ((adapterType == FruitProvider.class)|| (adapterType == ILabelProvider.class)|| (adapterType == IContentProvider.class)){ if (adaptableObject instanceof IApple) return getAppleProvider(); if (adaptableObject instanceof IOrange) return getOrangeProvider(); } return null; } public Class[] getAdapterList() { return TYPES; } protected AppleProvider getAppleProvider(){ if (appleProvider == null) appleProvider = new AppleProvider(); return appleProvider; } protected OrangeProvider getOrangeProvider(){ if (orangeProvider == null) orangeProvider = new OrangeProvider(); return orangeProvider; } } Listing 7: The fruit provider factory for displaying fruit in a JFace widget Listing 8: Registering the fruit provider adapter factory package com.jeffricker.fruit.provider; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; public abstract class FruitProvider implements ILabelProvider, IContentProvider { ... } /** * Provides the display of IApple objects */ public class AppleProvider extends FruitProvider{ public String getText(Object element){ ... } public Image getIcon(Object element){ ... } } /** * Provides the display of IOrange objects */ public class OrangeProvider extends FruitProvider { ... } Listing 9: The provider classes Real world example The Eclipse Communication Framework (ECF) began as a means of putting instant messaging in the Eclipse platform, but it has since expanded in scope to enable multiple means of data sharing in the Eclipse Rich Client Platform (RCP). ECF begins with a simple interface called a container and uses the IAdaptable pattern of Eclipse to achieve specific functionality. If we were using ECF for instant messaging, then we would focus on adapting the container for presence and other interfaces. Listing 10 shows how to create an ECF container. The container provides a generic means for handling any type of session level protocol. Listing 11 shows how to adapt a container for managing presence, a common feature of instant messaging. The container-adapter pattern decouples the session level protocols from the services provided over those protocols. // make container instance IContainer container = ContainerFactory.getDefault() .createContainer("ecf.xmpp"); // make targetID ID newID = IDFactory.getDefault() .createID("ecf.xmpp","[email protected]"); // then connect to targetID with null authentication data container.connect(targetID,null); Listing 10 Creating an ECF connection IPresenceContainer presence = (IPresenceContainer)container .getAdapter(IPresenceContainer.class); if (presence != null) { // The container DOES expose IPresenceContainer capabilities } else { // The container does NOT expose IPresenceContainer capabilities } Listing 11 Adapting a container for functionality The possibilities are sweeping. For instance, we can create our own adapter called IMarketDataContainer that provides streaming market data. We would create it the same way as IPresenceContainer. As shown in Listing 12, different market data providers might have different session level protocols, even proprietary protocols, but the containeradapter pattern would allow us to plug all of them in to our Eclipse RCP the same way. IContainer container = ContainerFactory.getDefault() .createContainer("md.nyse"); ID newID = IDFactory.getDefault().createID("md.nyse","[email protected]"); container.connect(targetID,null); IMarketDataContainer marketData = (IMarketDataContainer)container .getAdapter(IMarketDataContainer.class); Listing 12 New container types for ECF The adaptor pattern is a powerful tool which you will find used throughout the Eclipse platform. I hope with the hands-on, hand holding explanation in this article that you can now unleash that power in your own RCP applications.
April 9, 2008
by Jeffrey Ricker
· 40,339 Views
article thumbnail
Spring: How to Create Decoupled Swing Components
The Spring Framework's applicability in the context of Swing seems to be underhighlighted, at least when one looks around on the web.
April 5, 2008
by Geertjan Wielenga
· 61,782 Views
  • Previous
  • ...
  • 887
  • 888
  • 889
  • 890
  • 891
  • 892
  • 893
  • 894
  • 895
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×