27 February 2014

Removing an unresolved library reference from a netbeans project

When netbeans (v7) opens a project containing a library that is not in its libraries collection,
it proposes you to resolve the issue by creating this library.
Sometimes you do not need the library that is missing (e.g. because you have another library that you'd like to use instead).
You'd like to remove it, but that option is not proposed.
We'll need to play with netbeans project file to achieve this.

  1. Close the project.
  2. Navigate to the nbproject subdirectory of your project directory.
  3. Make a backup copy of  project.properties, just in case.
  4. Open project.properties and remove references to the library. For example to remove the "hibernate-persistence" library, you'll need to change
    javac.classpath=\
        ${libs.hibernate-persistence.classpath}
    to
    javac.classpath=

24 February 2014

Belgian e-government workflow

For registration, the login page for Belgian E-government and social security directs to your profile page.
On the profile page there is an other link for registration that directs you back to ... the login page.

https://www.socialsecurity.be/login/AuthenticationSelector?loginMethod=uId


22 February 2014

Jersey 1 filter classes

Classes in brown are also part of JAX-RS 2.
There's a small example of defining a JAX-RS 2 filter in the JAX-RS 2 preview post.


Microsoft cuts windows prices with 70% on cheap devices

Microsoft normally charges €50 for a pre-installed windows.
It has reduced this price to €15 for any device selling under €250, according to Bloomberg.
This is clearly a move to compete with tablets running Apple and Google software.

16 February 2014

New pests: featured news

Seems it is a new trend for service oriented sites to push at the top of their service a list of featured news they decided you want to see.

  • LinkedIn Pulse: 
  • my.yahoo aggregated home page now headlines featured news. 
    • In their tablet oriented redesign you can't have closed gadgets anymore either.
    • Time to move on: I relocated my home page to igHome. Liking it: good service with plenty of gadgets. They have tabbed aggregator pages  (which comes close to closed gadgets).

10 February 2014

Start Java DB: access denied ("java.net.SocketPermission" "localhost:1527" "listen,resolve")

Since Java 7u51 default network permissions have been restricted, hence Java can not connect to local network sockets by default.
To solve add to $JAVA_HOME/jre/lib/security/java.policy

grant codeBase "file:${java.home}}/../db/lib/*" {
   permission java
.net.SocketPermission "localhost:1527", "listen,resolve";
};
If Java DB (Apache Derby) is installed at another localtion, change the file:/... path accordingly.

Adding the permission line to the global permission section would allow access for all java applications
grant {
 // EXISTING line        // allows anyone to listen on un-privileged ports
 permission java.net.SocketPermission "localhost:0", "listen";
        // new line added
        permission java.net.SocketPermission "localhost:1527", "listen,resolve";
};
 You can specify port ranges, to allow access to all anonymous ports use
grant {
    permission java.net.SocketPermission "localhost:1024-", "listen,resolve";
};
java.net.SocketPermission JavaDoc

8 February 2014

Hibernate labs

Lab 1 Exercise 0

Adding Hibernate JPA 2 support (NetBeans < 7.2)

  1. Start the NetBeans IDE
  2. Select Tools > Libraries
    1. New Library...
      1. Library Name: HibernateJPA2
      2. Add Jar/Folder...
        1. Go to the $HOME/pkg directory and add jars as described here
    2. Click OK
  3. Select this library in subsequent exercises when you need to add a JPA 2 library

Lab 1 Exercise 2 Task 1: alternate instructions

Running the java DB Database

  1. If  required start the Java DB database server
    1. Select Window > Services to open the Services pane.
    2. Open the Services tab and expand Databases.
    3. Right-click JavaDB and select Start Server. 
      1. If you get a permission error, look here.
  2. Create an Employee database in NetBeans.
    1. Right-click JavaDB and select Create Database.
    2. Enter auction the database name.
    3. Enter student as the username.
    4. Enter student as the password. (Enter the password twice.)
    5. Click OK
  3. Right click the created database and click Connect

Lab 1 Exercise 2 Task 3: Hibernate instructions

Creating a Simple Entity

  1. Put the JDK level of your project to JDK 6 (the Hibernate 3.6 Modelgen module does not support JDK 7)
    1. Right click project => Properties
    2. Set Source/Binary format to JDK 6
  2. Create the Item entity class
    1. Right click JPA-03 in the Projects tab and choose New => Other => Persistence => Entity Class
    2. Type Item for the Class Name
    3. Type com.acme.entities for the package
    4. Click Next
    5. Make sure the persistence Unit Name is JPA-03PU
    6. Select Hibernate (JPA2) as the Persistence Library
    7. Choose the following for Database Connection:
      jdbc:derby://localhost:1527/auction [user on USER] 
    8. Select Create for the Table Generation Strategy.
    9. Click Finish.
  3. View the  persistence.xmlfile.
    1. Expand JPA-03 -> Source Packages -> META-INF.
    2.  Double-click  persistence.xml.
    3. After you have explored the Design view, click the Source button to
      explore the XML.
  4. Modify the Item entity
    1. Rename the primary key field to  itemId.
    1. Position the cursor on the id field and click CTRL-R
    2. Type  itemId in the New Name field
    3. Select Rename Getters and Setters
    4.  Click Refactor.
  5. Add the description, image, and inStock fields
    1. Press ALT+INSERT in the Item class and select Add Property...
    2. Set the name to description and click OK
    3. Add another property image
    4. Add another property inStock of Type Boolean
  6. Add constructors to the Item entity
    1. Press ALT+INSERT in the Item class and select Generate Constructor...
    2. Click Generate
    3. Generate another constructor with all fields to be initialised, except the itemId.
  7. Save the Item entity to the database
    1. Double click the jpa03.Main class
    2. Press ALT+INSERT in the class and select Use Entity Manager...
    3. Make the persist method static
    4. From the main method call the persist method and pass a new Item to it with these attributes
      • description: mouse pad
      • image: mousepad.jpg
      • inStock: true
  8. Add the Java DB client driver to the project
    1. Right-click Libraries under JPA-03 and choose AddJAR/Folder.
    2. Navigate to  $GLASSFISH_HOME\javadb\lib and select derbyclient.jar 
    3. Click OK
  9. Choose Run -> Run Main Project
  10. Verify that the  ITEM table has the new  INSTOCK field.
    a. Select the Services tab of the IDE.
    b. Expand the following JDBC Connection node:
    jdbc:derby://localhost:1527/auction [student on STUDENT]
    c. Expand the STUDENT -> Tables node.
    d. Right-click ITEM and choose Refresh.
  11. Verify that the  Item entity was saved to the database.
    a. Right-click the ITEM table and choose View Data

Lab 3 Exercise 2 Task 1: high level instructions

Adjusting the table and column names

  1. Create the com.acme.entities.AuctionUser entitiy
    1. Follow the same procedure as in Lab 1 Exercise 3 Task 3, steps 1-6
    2. Add the attributes shown in the Student Guide page 2-9, Figure 2-4
    3. Press ALT+INSERT to  add a default constructor and a constructor accepting all attributes except the auctionUserId
  2. Add an annotation to save the entity to the table A_USER
  3. Add an annotation to save the auctionUserId attribute to the id column
  4. Add an annotation to save the displayName attribute to the name column.
    1. Set the column length to 50.
  5. Modify the main method created in Lab 1 to save an AuctionUser entity
    1. Move the EntityManagerFactory local variable (and instantiation) to a private static attribute
    2. At the beginning of the method create auctionUser JaneDoe with email address jane@doe.com
    3. After the statement to persist the item, add a similar statement to persist the user
  6. Choose Run -> Run Main Project
  7. Follow the same procedure as in Lab 1 Exercise 3 Task 3, step 9 to run the project and verify the table was created as intended and JaneDoe was inserted.

Lab 4 Exercise 2 Task 1: Hibernate instructions

Customising the Persistence Unit

  1. Open META-INF/persistence.xml. Make sure that the view is set to Source.
  2. Add a <description> subelement to the <persistence-unit> element
    1. Add a new line below the <persistence-unit ... > tag.
    2. Type < and press CTRL+SPACE
    3. Choose description
    4. Complete the element by choosing </description>
    5. Add a body to the description element
      Hibernate/JavaDB PU
  3. Choose Run -> Run Main Project and correct any errors until the project runs well
  4. Select the <class> element that holds the Bid entity. From the menu bar use Source => Toggle comment, to comment out the element
  5. Add an XML element to exclude-unlisted-classes after the last class element.
  6. In the project view, right click the project and choose Clean and Build
  7. Choose Run -> Run Main Project. You should see an exception saying Bid is not recognised as an entity.
  8. Uncomment the Bid element
  9. Change the password in the persistence.xml file to force an authentication failure.
  10. Choose Run -> Run Main Project. You should see an exception signaling an authentication problem.
    1. Set the pasword back to its original value and set exclude-unlisted-classes to false
  11. Choose Run -> Run Main Project and correct any errors until the project runs well

Lab 4 Exercise 2 Task 2: High level instructions

Working with the entity manager

  1. In the Item entitiy
    1. Press ALT+INSERT to generate a constructor that takes all attributes except the id as an argument
    2. Press ALT+INSERT to generate a default constructor
  2. Create the ItemDao class in the (new) com.acme.daos package
    1. Add a static EntityManagerFactory attribute
      1. Initialize the attribute with an EntityManagerFactory for your persistence unit
    2. Implement the method
      private EntityManager getEntityManager()
      The method should return an EntityManager created from the EntityManagerFactory attribute
    3. Implement the method
      public Item save(Item item) 
      1. The method should call the getEntityManager method
      2. The method should persist the item within a transaction
        1. Look at the main method for inspiration
      3. return the item
  3. Create a unit test to test the save() method.
    1. Right-click the Project node and choose New –> Other.
    2. Select JUnit from the list of Categories and JUnit Test from the list of File Types, then click Next
      1. Type ItemTest for the class name
      2. Select Test Packages as the location
      3. Type com.acme.daos for the package name
      4. Click Finish. 
      5. Select JUnit 4.x if prompted for the JUnit version:
      6. Add an import for static assertXXX JUnit utility methods:
        import static org.junit.Assert.*;
      7. Add a static ItemDao attribute. Initialise it in the @BeforeClass annotated method.
      8. Create a test method called save() to test the save() method on the ItemDao
        1. Annotate the method with @Test
      9. In the test method
        1. Create a new Item and set all attributes except the id
        2. Save the Item using the ItemDao
        3. Use the assertFalse method to test the Item id is not null
        4. assertFalse("id should not be null", item.getId()==null);
        5. Right click ItemTest.java and choose Run File
        6. If you see a green bar with 100% in it, the test passed. If you see a red bar, the test failed.
    3. In the ItemDao class, implement the following method:
      public Item findByPrimaryKey(Long id)
    4. Create an annotated test method called find  in the ItemTest class to test the findByPrimaryKey method. In this method:
      1. Create a new Item and set all attributes except the id
      2. Save the Item using the ItemDao
      3. Pass the primary key of the saved item to findByPrimaryKey to retrieve the Item from the database
      4. Use the assertEquals method to test that the key of the returned Item has the same key.
      5. Run the test and correct errors until it succeeds.
      Optional steps
    5. Create a method in the ItemDao class.
      public void deleteByPrimaryKey(Long id) 
      1. Get an entity manager
      2. Start a transaction
      3. Look up the Item using the getReference method on the entity manager
      4. Delete the item using the remove method on the entity manager
      5. Commit the transaction
    6. Create an annotated test method called find in the ItemTest class to test the deleteByPrimaryKey method. in this method:
      1. Create a new Item and set all attributes except the id
      2. Save the Item using the ItemDao
      3. Pass the primary key of the saved item to deleteByPrimaryKey to delete the Item from the database
      4. Pass the primary key of the saved item to findByPrimaryKey to retrieve the Item from the database
      5. Use the AssertNull method to verify that the item is not found.

 Lab 5 Exercise 2 Task 1: High level instructions

  1. Creating a unidirectional One-to-One relationship between two entities

    1. Create the com.acme.entities.Auction entitiy with these attributes:
      private Long auctionId;
      private BigDecimal startAmount;
      private BigDecimal increment;
      private String status;
      private Date openTime;
      private Date closeTime;
      private Item item;
      
    2. Map the Date attributes to TIMESTAMP columns using the @Temporal annotation
    3. Establish a OneToOne relation with Item
    4. Press ALT+INSERT to generate getters and setters, a default constructor and a constructor accepting all attributes except the auctionId
    5. Create the com.acme.daos.AuctionDao class
      1. Implement similar methods as in ItemDao, but this time for the Auction entity
    6. Create a unit test to test the save() method.
      1. Right-click the Project node and choose New –> Other.
      2. Select JUnit from the list of Categories and JUnit Test from the list of File Types, then click Next
      3. Type AuctionTest for the class name
      4. Select Test Packages as the location
      5. Type com.acme.daos for the package name
      6. Click Finish. 
    7. Add an import for static assertXXX JUnit utility methods:
      import static org.junit.Assert.*;
    8.  Add an attribute
      static AuctionDao auctionDao;
    9. Initialise it in the @BeforeClass annotated method.
  2. Create a test method called save() to test the save() method on the ItemDao
    1. you may modify the method to pass the attributes in the constructor instead of using the setters
        @Test
        public void save(){
            Auction auction = new Auction();
            auction.setOpenTime(new Date());
            GregorianCalendar cal = new GregorianCalendar();
            cal.roll(Calendar.MONTH, true);
            auction.setCloseTime(cal.getTime());
            auction.setStartAmount(new BigDecimal("100.00"));
            auction.setIncrement(new BigDecimal("10.00"));
            auction.setStatus(Status.OPEN)
            auction = auctionDao.save(auction);
            assertTrue("id is greater than zero", auction.getAuctionId() > 0);
        }
    
  3. Right click ItemTest.java and choose Run File. Run the test and correct errors until it succeeds.

Lab 5 Exercise 3 Task 1: High level instructions

Creating a bidirectional One-to-Many/Many-to-One relationship

  1. Add a bidirectional One-to-Many/Many-to-One relationship between Auction (1) and Bid (many)
    1. Add an annotated bids attribute to the Auction entity
      1. Set cascade mode to ALL
      2. Initialize the attribute to an empty list of bids
    2. Add an auction attribute to the Bid entity
      1. Press ALT+INSERT to generate auction getter/setter methods
      2. Add an annotation for the relationship
      3. Press ALT+INSERT to generate a constructor that takes all attributes except the id as arguments
      4. Press ALT+INSERT to generate a default constructor
    3. Implement these methods in the Auction entity
      public void addBid(Bid bid)
      public int getBidCount()
  2. Implement a saveBids() methods in the AuctionTest class
    1. Create an auction
    2. Add 3 new bids with amounts of 150, 175 and 225
    3. Save the auction
    4. Assert that the saved auction got an ID
    5. Assert that the new auction has 3 bids
    6. Run the test until it passes.

 

Lab 6 Exercise 2 Task 1: High level instructions

Persisting an Entity with a superclass

  1. Create an entity called com.acme.entities BookItem.
  2. Make the BookItem entity a subclass of Item.
  3. The attributes of the entity are described in module 2 of the Student Guide.
  4. In the main method add the creation of a BookItem and save it to the database.
  5. Run the main method
  6. Examine which changes were made to the database tables

Lab 7 Exercise 2 Task 1: High level instructions

Persisting an Entity with an enum Field

  1. Create the Status enum.
    1. Right click on the com.acme.entities package and choose New>Java class
      1. Type Status for the Class Name.
      2. Choose enum for the type
    2. Click OK
  2. Add these values to the enum: OPEN, CLOSED, CANCELLED
  3. Refactor the type of Auction.status and change it to Status
    1. Change getter and setter methods
    2. Change the call to setStatus in AuctionTest.java
  4. Run the AuctionTest and correct errors until it succeeds
  5. Check the database definition of Auction.status and check the inserted data. What has changed?
  6. Add an Enumerated annotation to the status field and set enumeration type to STRING
  7. Run the AuctionTest and correct errors until it succeeds
  8. Check the database definition of Auction.status and check the inserted data. What has changed?

Lab 7 Exercise 3 Task 1: High level instructions

Persisting an Entity with a List field

  1. Add a Set of String keywords to the Item entity and initialize it to an empty Set.
  2. Annotate it as an ElementCollection
  3. Implement these methods:
    public void addKeyword(String keyword)
    public Collection<String> getKeywords()
  4. Add an annotated test method saveKeywords() to ItemTest. You can use the test methods for bids in Auction as a source of inspiration.
  5. Run the AuctionTest and correct errors until it succeeds.
  6. Describe the database table where the keywords are saved.

Lab 8 Exercise 2: High level instructions

Performing a query with the Java Persistence API QL

  1. Add a dynamicJpqlQuery() test to the ItemTest class. In the method
    1. Perform this JPQL query (within a transaction)
    2. DELETE FROM Item i
      1. What does this query do?
    3. Create 3 Items using ItemDao.save(Item i), using different values for all atributes.
    4. Save them to the database
    5. Perform a JPQL query to retrieve  them
    6. Assert you retrieved 3 results
    7. perform a  JPQL query to retrieve only items in stock
    8. Assert you retrieved the correct number of results
  2. Optional: Add a testPaging() test method that creates 25 Items and retrieves them in groups of maximum 10. Verify that it runs correctly.

Lab 8 Exercise 3: High level instructions

Performing a query with SQL

  1. Copy the dynamicJpqlQuery() test in the ItemTest class to nativeSqlQuery()
  2. In the method replace all queries with native queries

Lab 8 Exercise 4: High level instructions

  1. Copy the CriteriaTest.java file from the labs08 directory in the solutions to the com.acme.entities package in the test directory
  2. Examine the code
  3. Run the code

Lab 9 Exercise 2 Task 1

Creating and running a named query

  1. Define a named query called ClearAuctions using an annotiation on the Auction entity that deletes all auctions
  2. Define a named query called FindByStatusAuctions using an annotiation on the Auction entity. To define multiple named queries use @NamedQueries:
    @NamedQueries( {
        @NamedQuery(name="xxx",query="XXXX"), 
        @NamedQuery(name="yyy",query="YYY") }
    1. The query should select all auctions with a certain status
    2. Set the status in the query as a named parameter
  3. Add an annotated test method called testNamedQuery() to the AuctionTest clas.
  4. Execute the ClearAuctions query (you can find inspiration in the tests in the previous chapter)
    • Do not use the Dao, but create an EntityManager
    • Perform the delete operation within a transaction
  5. Execute the FindByStatusAuctions query to look for all closed auctions
  6. Assert no entries are found
  7. Run the test and correct errors until it succeeds
  8. Modify the testNamedQuery() test to insert three auctions and add them to the auction table
    1. Add a convenience constructor with common attributes and a default constructor to the entity
    2. The start date of the first auction should be between those of the second and the third item(we will use this in the next exercise)
    3. Only two auctions should be in open
    4. Save them using the Dao
  9. Assert one entry is found
  10. Run the test and correct errors until it succeeds

Lab 9 Exercise 2 Task 2

Creating multiple named queries

  1. Write a new NamedQuery FindAllAuctions that finds all auctions.
  2. Copy the testNamedQuery() test to a new test and call it testOrderedQuery()
  3. Replace the last query in the copied test method (FindByStatusAuctions) with the FindAllAuctions Query and store the results in a List
  4. Assert that the first auction starts after the second.
  5. Run the test and correct errors until it succeeds
  6. Write a new NamedQuery called FindAllOrderByOpenTimeAuctions that sorts by ascending openTime.
  7. Add the query at the end of testOrderedQuery.
  8. Assert that the first auction starts before the second.

 

Lab 10 Exercise 2

Performing a Query With Multiple Criteria

  1. Define a named query called clearItems that deletes all items. Use an annotation on the Item entity
  2. Add an annotated test method called incompleteItems() to the ItemTest class.
  3. In the incompleteItems method
    1. Call the clearItems named query
    2. Create 3 items.
      1. An Item with a description
      2. An Item with an image
      3. An Item with an image and a description
           (Use test methods from previous labs for inspiration)
  4. Build a criteria query that selects all items that have a description OR an image that is NULL
    Hint: use static methods in Restrictions
  5. Execute the query
  6. Assert 2 entries are found
  7. Run the test and correct errors until it succeeds

Lab Design Patterns Exercise 1

In this lab you will build a superclass with common behaviour for Data Access Objects.
To keep things simple, this template supposes that all primary keys are of type Long.

  1. Copy the GenericJpaDao template from $HOME/labs/lab_design to the com.acme.daos package.
  2. Implement the empty methods (look for //TODO comments)
    1. Use the TClass attribute whenever you need to supply the entity class
  3. Adapt the class that interacts with the database for Item entities to use GenericJpaDao 
    1.  Let the class inherit from GenericJpaDao
public class ItemDao extends GenericJpaDao<Item> 
    1.  Refactor all methods in the ItemDao so there names match the names used in GenericJpaDao (Refactoring will update all classes that use these methods to use the new names)
      1. Then delete these methods
    2. In the Item Test class
      1. Create attributes
private static EntityManagerFactory emf;
private static ItemDao itemDao;

      1. If not yet present, create a method
      2. @BeforeClass public static void setUpClass(){}
      3. In the method
        1. create a factory with the name of your persistence unit
        2. call itemDao.setEntityManagerFactory(emf);
      4. Create a static attribute for the ItemDao and assign an instance to it in SetUpClass()
      5. Review your test methods and use the created Data Access Object in them
    1. Run the tests until they succeed
  1. Write down some suggestions for enhancing the GenericJpaDao class

Lab Performance Exercise 1

Using data filters

  1. Define a filter called BidsApproved that limits bids to those that have their approval set to "OK"
  2. Annotate the Bid class to associate the filter BidsApproved with it.
  3. Write a test method called testApprovedBids(). In the testmethod
    1. Initialize test data
      1. Clear all the Bids from the database
      2. Clear all the Auctions from the database
      3. Create an Auction
      4. Create 3 bids
        1. Only one bid should have approved set to "OK"
        2. All bids should be associated with the Auction
        3. Add all bids to the Auction (bidirectional relation)
      5. Save the Auction
    2. Enable the BidsApproved filter
    3. Select all the bids
    4. Assert that only one bid is returned
    5. Disable the BidsApproved filter
    6. Run the test and correct errors until it succeeds
  4. Extend the test method (just before disabling the bidsApproved filter
    1. Select all the Auctions
    2. Get all the Bids from the first Auction that is returned
    3. Assert that only one bid is returned
    4. disable the  BidsApprovedfilter at the end of te
    5. Run the test and write down the result
  5. Activate the filter on the bids Collection
    1. In the Auction class, annotate the bids attribute with the BidsApproved filter
    2. Run the test and correct errors until it succeeds

Lab Performance Exercise 2

Adding L2 EhCache support

  1. In the projects tab, right click the Libraries folder and choose "Add Jar/Folder..."
    1. Go to the $HOME/pkgpkg/ehcache/lib directory and add the ehcache-core jar
  2. Add caching support to persistence.xml
    1. Set the hibernate.cache.use_second_level_cache property to true
    2. Add the EhCache provider 
    3.  <property name="hibernate.cache.region.factory_class"
       value="org.hibernate.cache.SingletonEhCacheRegionFactory"/>
  3. For monitoring
    1. set the hibernate.generate_statistics property to true
    2. Make sure you log Hibernate generated SQL

Caching the Item entity

  1. Add READ_ONLY caching to the Item entity using the @Cache annotation (from org.hibernate.annotations)
  2. Add an annotated test method called testReadCache() to the ItemTest class. Throughout this exercise, print out what you are doing before each database access, to make your test output easier to follow. In the test method do these actions:
    1. Create a org.hibernate.stat.Statistics objec
      1. Get a hibernate SessionFactory from the EntityManagerFactory
      2. Get the Statistics object from the SessionFactory
    2. Create an Item, save it and get its ID
    3. Print out cache hits and misses
    4. Lookup the Item again, using the ID
    5. Print out cache hits and misses
    6. Lookup the Item again, using the ID
    7. Print out cache hits and misses
  3. Run the tests and correct any errors. Observe the cache behaviour. Observe that the generated SQL statements are not printed when the cache is used.
  4. At the end of the test method add code to:
    1. Evict everything from the cache
    2. Lookup the Item
    3. Print out cache hits and misses
  5. Run the tests and correct any errors. Observe the cache behaviour.
  6. At the end of the test method add code to:
    1. Modfy the description of the Item to "changed"
    2. Merge the saved Item to the database
      1. Add an update(Item it) method to the ItemDao class for this (if it did not exist yet).
    3. Lookup the Item
    4. Print out cache hits and misses
    5. Assert that the description of the looked up Item is set to "changed"
  7. Run the test. Record the cache behaviour. An exception can be thrown. 
  8. Modify the Item caching concurrency annotation to NONSTRICT_READ_WRITE
  9. Run the test until it succeeds. Record the cache behaviour and compare with the previous result.
  10. Modify the Item caching concurrency annotation to READ_WRITE
  11. Run the test until it succeeds. Record the cache behaviour and compare with the previous result.

Caching the keywords collection

  1. In the testReadCache() method, add some keywords to the Item, before it is initially saved to the database.
  2. At the end of the method, add these instructions (remember to add some tracing statements as well):
    1. get the number of keywords associated with the Item
    2. Print out cache hits and misses 
    3. Lookup the Item again, using the ID
    4. Print out cache hits and misses
    5. get the number of keywords associated with the Item
    6. Print out cache hits and misses
  3. Run the test. Record the cache behaviour.
  4. Annotate the keywords collection to cache it with READ_WRITE concurrency
  5. Run the test until it succeeds. Record the cache behaviour and compare with the previous result.


7 February 2014

Olympic winter games doodle

The doodle is accompanied by an extract of the Olympic Charter that links sports and human rights. The rainbow colours are another reference to Gay rights.
Without formulating an explicit company message, this must be the most political doodle ever.


3 February 2014

JPA 2.x what's new (edit)

JPA 2 (JSR 317) is a superset of JPA 1 and part of Java EE6. Added features include:

  • Entities
    • mixing of field and getter method annotations
    • JSR 303 validation
  • Relations
    • unidirectional OneToMany
    • use JoinTable for all relation cardinalities
  • Automatic actions upon Entity changes
    • CascadeType.DETACH
    • orphanRemoval: delete an orphan Entity if its relation to its parent Entity is broken
  • Collections
    • Support for mapping collections of Basic and Embeddable types (@ElementCollection)
    • Map keys and values can both be Basic, Embeddable and Entity types
  • Embeddables
    • Can be nested
    • Can have attributes with relations
    • Can inherit from a MappedSuperclass
  • Ordering
    • @OrderBy: determine order in which elements of List attributes are loaded
    • @OrderColumn: support for preserving List order in the database using an OrderColumn
  • Queries
    • TypedQuery <T>
    • Criteria API
      • metamodel generation
    • JPQL
      • functions and operations in SELECT clause
      • COALESCE function (returns first non null argument)
      • TYPE function: get class of Entity to compare with literal
      • CASE expression
      • KEY, VALUE, and ENTRY keywords for map operations
      • use of enums
      • enum and temporal literals
  • Locking
    • pessimistic locking support
    • lock mode arguments in EntityManager methods
  • Cache API
JPA 2 is implemented in Hibernate 3.5+

JPA 2.1 (JSR 338) is part of Java EE 7. Added features include:

  • StoredProcedureQuery
  •   StoredProcedureQuery proc = em.createStoredProcedureQuery("squareRoot");
      proc.registerStoredProcedureParameter("square", Double.class, ParameterMode.IN);
      proc.registerStoredProcedureParameter("root", Double.class, ParameterMode.OUT);
      proc.setParameter("square", 338.0);
      proc.execute();
      Double result = (Double)storedProcedure.getOutputParameterValue("root");
    
  • @Converter/@Convert: write custom code to convert java data to/from database data
  • JPQL 
    • selectively  access  entity subclasses: TREAT (relation.parentEntityAttribute AS  childEntity)
    • support for predefined and user defined database functions: FUNCTION(name,args...)
          WHERE FUNCTION (isAllowed, theater.movie, user.age)
  • update and delete using the Criteria API
  • Standardised schema generation properties 
  • Entity Graphs allow runtime control over which parts of an entity are fetched. Here's an example:
  • @Entity
    @NamedEntityGraph(name="withBids", attributeNodes={@NamedAttributeNode("bids")})
    public class Auction
    {...}
    • The Auction above has bids that are normally lazily loaded.
    • Using the entity graph you can ask for a variant where the bids are eagerly loaded:
    Properties prop = new Properties();
    prop.put("javax.persistence.loadgraph", em.getEntityGraph("withBids"););
    Auction eagerBids= em.find(Auction.class, auction_id, prop); 
    •  In addition to declaring the graph with annotations, you can construct it at runtime with an API
    • The graph can also be set as a hint to a query
JPA 2.1 is implemented in Hibernate 4.3+

2 February 2014

startWebLogic: maximum number of socket reader threads allowed by the configuration is: 4

I am running Weblogic 12c 12.1.1 which I installed from the zip archive downloaded from the Oracle webpage on windows 7 64bit, using a Java 7 64 bit JVM.

When starting WebLogic I had this error message: <BEA-000402> <There are: 5 active sockets, but the maximum number of socket reader threads allowed by the configuration is: 4. You may want to alter your configuration>

My settings in the WebLogic Administrator Console indicated that I was using native I/O, so the configuration seemed fine.

However, earlier in the logs I also had this warning:
<BEA-000438> <Unable to load performance pack. Using Java I/O instead. Please ensure that wlntio.dll is in: C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;...

I found wlntio.dll in %WL_HOME%\server\native\... subdirectories for different platforms. Apparently this had not been added to the startup configuration, because I did not run an installer, but installed from the zip file. I added the directory in wich the dll lives to the PATH in the startupscript  ...\weblogic\domain1\bin\setDomainEnv.cmd:

set WL_HOME=C:\java\weblogic\12.1.1\wlserver
@REM added the next line
set PATH=%WL_HOME%\server\native\win\x64;%PATH%


Now all's well :)

Creating a JAX-WS Dispatch client using JAXB

import cards.*;
import java.util.logging.*;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import javax.xml.ws.*;
import javax.xml.ws.soap.SOAPBinding;

public class CardDeckSEJaxbDispatchClient {

    private static final String URI = "http://ejbs/";
    public static final String NS = "ns1";

    public static void main(String[] args) {
        Service svc = Service.create(new QName(
            URI,
            "CardDeckSessionBeanService"));
        final QName portName = new QName(URI, "CardDeckSessionBeanPort");
        svc.addPort(portName,
            SOAPBinding.SOAP11HTTP_BINDING,
            "http://localhost:7001/CardDeckSessionBean/CardDeckSessionBeanService");
        try {
             // cards is a package with JAXB classes
             Dispatch<Object> dispatch = svc.createDispatch(portName,
                JAXBContext.newInstance("cards"),
                Service.Mode.PAYLOAD);
            // objectfactory is generated by wsimport
            ObjectFactory of = new ObjectFactory();
            // create deck
            CreateDeck createParam = of.createCreateDeck();
            createParam.setArg0(1);
            JAXBElement<CreateDeckResponse> createResponse
                = (JAXBElement<CreateDeckResponse>) dispatch.
                    invoke(of.createCreateDeck(createParam));
            int deckId = createResponse.getValue().getReturn();
            System.out.println("\nDeck ID = " + deckId);
            // getDeck
            GetDeck getParam = of.createGetDeck();
            getParam.setArg0(deckId);
            JAXBElement<GetDeckResponse> getResponse = 
                (JAXBElement<GetDeckResponse>) dispatch.
                invoke(of.createGetDeck(getParam));
            StackType deck = getResponse.getValue().getReturn();
            for (CardType card : deck.getCard()) {
                System.out.println(
                    card.getRank()
                    + " OF "
                    + ("JOKER".equals(card.getRank()) ? card.getColor() : card.getSuit()));
            } // end for all cards in deck
        } catch (JAXBException ex) {
            Logger.getLogger(CardDeckSEJaxbDispatchClient.class.getName()).
                log(Level.SEVERE, null, ex);
        } // end catch
    } // end main
} // end class

Creating a JAX-WS based Dispatch client

import java.io.IOException;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.*;
import javax.xml.ws.soap.SOAPBinding;

public class DispatchClient {

    public static void main(String args[]) {

        String svcNamespace = "http://cater.com/";
        String prefix = "ns1";

        Service svc = Service.create(new QName(svcNamespace, "stockService"));
        QName portQName = new QName(svcNamespace, "stockPort");
        svc.addPort(portQName,
            SOAPBinding.SOAP11HTTP_BINDING,
            "http://localhost:7001/Stock/StockService");
        Dispatch<SOAPMessage> dispatch = svc.createDispatch(portQName,
            SOAPMessage.class,
            Service.Mode.MESSAGE);
        try {
            MessageFactory msgFactory = MessageFactory.newInstance(
                SOAPConstants.SOAP_1_1_PROTOCOL);
            SOAPMessage request = msgFactory.createMessage();
            request.getSOAPBody().
                addChildElement("getBeersFrom", prefix, svcNamespace).addChildElement(
                    "arg0").
                addTextNode("Belgium");
            SOAPMessage response = dispatch.invoke(request);
            response.writeTo(System.out);
        } catch (SOAPException | IOException ex) {
            ex.printStackTrace();
        }
    } // end main
} // end class

Netbeans 7.4 and Java 8 preview (update)

The Netbeans 7.4 release candidate is out (update: full release is out now). Here's an overview of interesting new Java features (there's also PHP, C, C++ support) .

  • JDK8 preview support
    • debugger support for lambda expressions
  • Easy browser/mobile switcher

  • client network monitor
    •  In addition to the server side HTTP monitor for some application servers, NetBeans now has a client side network monitor for the internal browser and NetBeans Chrome plugin
  • Pure Editor Mode: View > Show Only Editor lets the editor take the entire NetBeans window, giving you the light feel of a basic editor like notepad++
  • Code completion
    • second CTRL-SPACE completes code one level down the members chain

    • Substring completion (in addition to exisiting starts with string completion)
  • folding
    • code folding shows number of hidden lines
    • folding support in output window (e.g. exceptions in stack traces)
  • JSON navigator and code folding
  • Debugger: go to source code of variable type
  • Lock contention profiling
  • diff between version control branches
  • tooltips of search results show surrounding lines
Here's the complete list