Featured FREE Whitepapers

What's New Here?


Using Oracle AQ in Java Won’t Get Any Easier Than This

As recently announced in our newsletter, the upcoming jOOQ 3.5 will include an awesome new feature for those of you using the Oracle database: Native support for Oracle AQ! And your client code will be so easy to write, you’ll be putting those AQs all over your database immediately. How does it work? jOOQ rationale The biggest reason why many of our users love jOOQ is our code generator. It generates a Java representation of your database schema, with all the relevant objects that you need when writing SQL. So far, this has included tables, sequences, user-defined-types, packages, procedures. What’s new is that AQ objects are now also generated and associated with the generated object type. A simple schema Let’s consider writing this simple schema (all sources available on GitHub) CREATE OR REPLACE TYPE book_t AS OBJECT ( ID NUMBER(7), title VARCHAR2(100 CHAR), language VARCHAR2(2 CHAR) ) /CREATE OR REPLACE TYPE books_t AS VARRAY(32) OF book_t /CREATE OR REPLACE TYPE author_t AS OBJECT ( ID NUMBER(7), first_name VARCHAR2(100 CHAR), last_name VARCHAR2(100 CHAR), books books_t ) /CREATE OR REPLACE TYPE authors_t AS VARRAY(32) OF author_t /BEGIN DBMS_AQADM.CREATE_QUEUE_TABLE( queue_table => 'new_author_aq_t', queue_payload_type => 'author_t' );DBMS_AQADM.CREATE_QUEUE( queue_name => 'new_author_aq', queue_table => 'new_author_aq_t' );DBMS_AQADM.START_QUEUE( queue_name => 'new_author_aq' ); COMMIT; END; / So, essentially, we have both OBJECT and VARRAY types for books and authors. You might prefer using TABLE types rather than VARRAY types, but for the sake of simplicity, we stick with VARRAY (as it isn’t so easy to use nested TABLE types with AQs in Oracle). We have also created a queue that notifies listeners every time a new author is added to the database – along with their books. Imagine enqueue operations being done in a trigger on either the author or the book table. jOOQ-generated code When you run the jOOQ codegenerator (version 3.5 upwards) against the above schema, you’ll get a new Queues.java file, which contains: public class Queues { public static final Queue<AuthorT> NEW_AUTHOR_AQ = new QueueImpl<AuthorT>( "NEW_AUTHOR_AQ", SP, AUTHOR_T); } Obviously, also the previously shown OBJECT and VARRAY types are also generated by jOOQ, just like lables. (of course, the actual naming patterns for generated Java code are completely configurable) Using the generated artefacts The above code is not really nicely formatted on this blog, but you don’t see any of this in your every day work. Because when you want to enqueue a message to this queue, you can simply write: // Create a new OBJECT type with nested // VARRAY type AuthorT author = new AuthorT( 1, "George", "Orwell", new BooksT( new BookT(1, "1984", "en"), new BookT(2, "Animal Farm", "en") ) );// ... and simply enqueue that on NEW_AUTHOR_AQ DBMS_AQ.enqueue(configuration, NEW_AUTHOR_AQ, author); Seriously? That easy? Yes! Compare the above to anything you’ve written before through JDBC, or using Oracle’s native APIs. You’ll find a couple of examples about how to serialise / deserialise RAW types, but frankly, queues are awesome because you can send OBJECT types through the database, and we don’t see those examples from Oracle. In fact, trust us, you don’t want to serialise OBJECT, VARRAY, or TABLE types through JDBC. You don’t. That’s our job. We’re hacking JDBC so you don’t have to. Of course, you can also pass MESSAGE_PROPERTIES_T, ENQUEUE_OPTIONS_T, and DEQUEUE_OPTIONS_T types as arguments to the enqueue() and dequeue() methods. Dequeuing is just as easy. The following will generate a blocking call and wait for the next AUTHOR_T message to arrive: AuthorT author = DBMS_AQ.dequeue(configuration, NEW_AUTHOR_AQ); That’s it. Can’t be that hard, can it?Goodie: Java 8 and Oracle AQ With the above simple API and Java 8, we can do what Oracle must’ve known long ago, when they renamed Oracle AQ’s marketing name to Oracle Streams. Let’s create a Java 8 Stream of AQ-produced OBJECT types with jOOQ. Easy as pie. Just write: static <R extends UDTRecord<R>> Stream<R> stream( Configuration c, Queue<R> queue ) { return Stream.generate(() -> DBMS_AQ.dequeue(c, queue) ); } And now, use this beauty like so: stream(configuration, NEW_AUTHOR_AQ) .limit(10) .forEach(author -> { System.out.println( author.getFirstName() + " " + author.getLastName()); }); The above statement takes the next 10 messages dequeued this way and prints them to the console.Reference: Using Oracle AQ in Java Won’t Get Any Easier Than This from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog....

How to Load Resources from Classpath in Java with Example

Classpath in Java is not only used to load .class files, but also can be used to load resources e.g. properties file, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL. Suppose, you have a properties file inside config folder of your project, and you want to load that properties file, how do you do that? Similarly, you have icons and thumbnails for your web applications on icons directory of your project, how do you load them? Answer is by using java.lang.Class’getResource() and getResourceAsStream() method. These method accepts path of resource as String and returns URL and InputStream respectively. You can obtain a reference of Class by calling either getClass() method or by using class literal. If you have an object, then you can call getClass() because its a non-static method, on the other hand, if you don’t have any object, you can simply use .class with name of any class e.g. Sample.class will give you reference of java.lang.Class. These methods are available from JDK 1.1 and you can even use them anywhere you have access to core Java library. If you are creating J2ME games or application, you can use these method to load icons and tiles for your game, and all other resource for your application as well. How does getResourceAsStream works Internally this method delegate the loading request of resource to its class loader. If you call getResourceAsStream() method on an object which is loaded by BootStrap ClassLoader then it will delegate it to ClassLoader.getSystemResourceAsStream(java.lang.String) method. We pass path of resource to this method but rules for searching resources associated with a given class are implemented by the defining class loader of the class. Since you can pass both absolute and relative path to Class.getResourceAsStream(), but ClassLoader.getResourceAsStream() takes an absolute path, that’s why an absolute resource name is constructed from the given resource name using following algorithm : If the name begins with a ‘/’ (‘\u002f’), then the absolute name of the resource is the portion of the name following the ‘/’. Otherwise, the absolute name is of the following form: modified_package_name/name where the modified_package_name is the package name of this object with ‘/’ substituted for ‘.’ (‘\u002e’). This means, the resource name passed to the method should look like /com/abc/config/app.properties if the app.properties is stored in the com.abc.config package instead of the current class’s. If you look at the code of java.lang.Class in Eclipse IDE by using short-cut Ctrl+T and typing java.lang.Class, you can see how this method works : public InputStream getResourceAsStream(String name) { name = resolveName(name); ClassLoader cl = getClassLoader0(); if (cl==null) { // A system class. return ClassLoader.getSystemResourceAsStream(name); } return cl.getResourceAsStream(name); }This algorithm is implemented at resolveName() method, as seen below : /** * Add a package name prefix if the name is not absolute Remove leading "/" * if name is absolute */ private String resolveName(String name) { if (name == null) { return name; } if (!name.startsWith("/")) { Class c = this; while (c.isArray()) { c = c.getComponentType(); } String baseName = c.getName(); int index = baseName.lastIndexOf('.'); if (index != -1) { name = baseName.substring(0, index).replace('.', '/') +"/"+name; } } else { name = name.substring(1); } return name; } Main problem comes while loading resource using getResourceAsStream() method is NullPointerException, because this method return null if its not able to find the resource. In following example, we have a Eclipse project, and I have created a properties file called app.properties inside config directory. Now to load that file, I just need to pass “app.properties”, if I pass anything like “config/app.properties” or “/config/app.properties” getResourceAsStream() will return null, and code will subsequently throw NullPointerException as shown below : Exception in thread "main" java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Unknown Source) at java.util.Properties.load0(Unknown Source) at java.util.Properties.load(Unknown Source) at Test.main(Test.java:29) to avoid this error you must check output of getResourceAsStream() before using it, defensive programming is there just because of this kind of methods. Java Program to load Resource from Classpath Here is our complete Java program to load images, resources, text file or binary file from classpath in Java, resource can be anything, what is important is that it must be accessible. package test;import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties;/** * Java Program to demonstrate how to load resources e.g. properties file from * classpath. There are two ways to load resources in Java, one by using * getResourceAsStream() and getResource() method from java.lang.Class. Main * difference between these two methods are that one returns an InputStream * while other returns a URL object. * * @author Javin Paul */ public class ResourceLoader{public static void main(String args[]) {// loading resource using getResource() method InputStream in = Test.class.getResourceAsStream("app.properties");Properties config = new Properties(); try { config.load(in); System.out.println(config.getProperty("name")); System.out.println(config.getProperty("version"));} catch (IOException e1) { e1.printStackTrace(); }// loading resource using getResourceAsStream() method URL resourceURL = Test.class.getResource("app.properties"); Properties appConfig = new Properties(); try { appConfig.load(resourceURL.openStream()); System.out.println(appConfig.getProperty("name")); System.out.println(appConfig.getProperty("version"));} catch (IOException e) { e.printStackTrace(); }}}Output: SampleApp 1.0.0 SampleApp 1.0.0 If you look closely you will find that we have used both getResource() and getResourceAsStream() method to load resource from classpath in Java, in this case just properties file. First example looks more cleaner than second example because we don’t need to open an explicit stream, getResourceAsStream() method returns an InputStream, which can be used anywhere. That’s all on how to load resources from class-path in Java.Reference: How to Load Resources from Classpath in Java with Example from our JCG partner Javin Paul at the Javarevisited blog....

Introducing the JBoss BPM Suite installer

This week we want to introduce you to the rather unknown installer component that is delivered with the JBoss BRMS and JBoss BPM Suite products. Note that all the current demo projects have been requiring you to download the JBoss BPM Suite deployable eap zip product file and JBoss EAP 6.1.1 zip product file. Moving forward we will migrate all our projects to make use of just the JBoss BPM Suite installer jar file. This includes mulit-product demo projects, where JBoss BRMS or JBoss BPM Suite is used we will be integrating the automated installations by using the installer  component. In this article we will demonstrate its usage and introduce it as a standard way of implementing all our installations. JBoss BPM Suite install demo This project is the most basic installation you can achieve with the product, just installed, configured to use a single user (erics) with all the roles available in the BPM Suite. The project readme file on github presents you will all the steps needed to install this project and the JBoss BPM Suite online workshop has been updated to lead you through this installation using the new installer component. QuickstartDownload and unzip. Add product installer to installs directory. Run ‘init.sh’ or ‘init.bat’ file. Login to http://localhost:8080/business-central (u:erics / p:bpmsuite1!) Enjoy installed and configured JBoss BPM Suite.The installation will run a bit longer and setup a secured password vault, preset users with new stronger password, and fully automate your JBoss BPM Suite setup.When it is done running you can fire up the product as the console output will show and login using the provided user.If you are interested you can look in the support directory for the script file that automates the installation and the variable file that is used to install standard users. Examine the init scripts to see that the installation is run by pointing to these files with the command: $ java -jar {bpms-install.jar} support/installation-bpms -variablefile support/installation-bpms.variables Also note that many demo will now be starting the installation with “Download and unzip.”, meaning you can just click on this link to obtain the project instead of having to have git installed and cloning the project. The JBoss BRMS product install demo is also available with this new usage of the installer component. Now your usage and setup of JBoss BPM Suite and our demo projects is just that much easier to enjoy!Reference: Introducing the JBoss BPM Suite installer from our JCG partner Eric Schabell at the Eric Schabell’s blog blog....

Adding Custom Claims to the SAML Response – (How to Write a Custom Claim Handler for WSO2 Identity Server)

Overview The latest release of WSO2 Identity Server (version 5.0.0), is armed with an “application authentication framework” which provides lot of flexibility in authenticating users from various service providers who are using heterogeneous protocols. It has several extension points, which can be used to cater several customized requirements commonly found in enterprise systems. With this post, I am going to share the details on making use of one such extension point.       Functionality to be Extended When SAML Single Sign On is used in enterprise systems it is through the SAML Response that the relying party get to know whether the user is authenticated or not. At this point relying party is not aware of other attributes of the authenticated user which it may need for business and authorization purposes. To provide these attribute details for the relying party, SAML specification has allowed to send attributes as well in the SAML Response. WSO2 Identity Server supports this out of the box via the GUI provided for administrators. You can refer [1] for the details on this functionality and configuration details. The flexibility provided by this particular extension, comes handy when we have a requirement to add additional attributes to the SAML Response, apart from the attributes available in the underline user store. There may be external data sources we need to look, in order to provide all the attributes requested by the relying parties. In the sample I am to describe here, we will be looking into a scenario where the system needs to provide some local attributes of the user which are stored in user store, with some additional attributes I expect to be retrieved from an external data source. Following SAML Response is what we need to send to the relying party from WSO2 IS. <saml2p:Response Destination="https://localhost:9444/acs" ID="faibaccbcepemkackalbbjkihlegenhhigcdjbjk" InResponseTo="kbedjkocfjdaaadgmjeipbegnclbelfffbpbophe" IssueInstant="2014-07-17T13:15:05.032Z" Version="2.0" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">localhost </saml2:Issuer> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> .......... </ds:Signature> <saml2p:Status> <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/> </saml2p:Status> <saml2:Assertion ID="phmbbieedpcfdhcignelnepkemobepgaaipbjjdk" IssueInstant="2014-07-17T13:15:05.032Z" Version="2.0" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">localhost</saml2:Issuer> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> ......... </ds:Signature> <saml2:Subject> <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">Administrator</saml2:NameID> <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> <saml2:SubjectConfirmationData InResponseTo="kbedjkocfjdaaadgmjeipbegnclbelfffbpbophe" NotOnOrAfter="2014-07-17T13:20:05.032Z" Recipient="https://localhost:9444/acs"/> </saml2:SubjectConfirmation> </saml2:Subject> <saml2:Conditions NotBefore="2014-07-17T13:15:05.032Z" NotOnOrAfter="2014-07-17T13:20:05.032Z"> <saml2:AudienceRestriction> <saml2:Audience>carbonServer2</saml2:Audience> </saml2:AudienceRestriction> </saml2:Conditions> <saml2:AuthnStatement AuthnInstant="2014-07-17T13:15:05.033Z"> <saml2:AuthnContext> <saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef> </saml2:AuthnContext> </saml2:AuthnStatement> <saml2:AttributeStatement> <saml2:Attribute Name="http://wso2.org/claims/role" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"> <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string"> Internal/carbonServer2,Internal/everyone </saml2:AttributeValue> </saml2:Attribute> <saml2:AttributeStatement> <saml2:Attribute Name="http://pushpalanka.org/claims/keplerNumber" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"> <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string"> E90836W19881010 </saml2:AttributeValue> </saml2:Attribute> <saml2:Attribute Name="http://pushpalanka.org/claims/status" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"> <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string"> active </saml2:AttributeValue> </saml2:Attribute> </saml2:AttributeStatement> </saml2:AttributeStatement> </saml2:Assertion> </saml2p:Response> In this response we are having one local attribute, which is role and two additional attributes http://pushpalanka.org/claims/keplerNumber and http://pushpalanka.org/claims/status which have been retrieved from some other method we can define in our extension. How?Implement the customized logic to get the external claims. There are just two facts we need to note at this effort.The custom implementation should either implement the interface ‘org.wso2.carbon.identity.application.authentication.framework.handler.claims.ClaimHandler’ or extend the default implementation of the interface ‘org.wso2.carbon.identity.application.authentication.framework.handler.claims.impl.DefaultClaimHandler’. The map returned at the method, ‘public Map<String, String> handleClaimMappings’ should contain all the attributes we want to add to the SAML Response.Following is the sample code I was written, adhering to the above. The external claims may have been queried from a database, read from a file or using any other mechanism as required. public class CustomClaimHandler implements ClaimHandler {private static Log log = LogFactory.getLog(CustomClaimHandler.class); private static volatile CustomClaimHandler instance; private String connectionURL = null; private String userName = null; private String password = null; private String jdbcDriver = null; private String sql = null;public static CustomClaimHandler getInstance() { if (instance == null) { synchronized (CustomClaimHandler.class) { if (instance == null) { instance = new CustomClaimHandler(); } } } return instance; }public Map<String, String> handleClaimMappings(StepConfig stepConfig, AuthenticationContext context, Map<String, String> remoteAttributes, boolean isFederatedClaims) throws FrameworkException {String authenticatedUser = null;if (stepConfig != null) { //calling from StepBasedSequenceHandler authenticatedUser = stepConfig.getAuthenticatedUser(); } else { //calling from RequestPathBasedSequenceHandler authenticatedUser = context.getSequenceConfig().getAuthenticatedUser(); }Map<String, String> claims = handleLocalClaims(authenticatedUser, context); claims.putAll(handleExternalClaims(authenticatedUser));return claims; }/** * @param context * @return * @throws FrameworkException */ protected Map<String, String> handleLocalClaims(String authenticatedUser, AuthenticationContext context) throws FrameworkException { .... }private Map<String, String> getFilteredAttributes(Map<String, String> allAttributes, Map<String, String> requestedClaimMappings, boolean isStandardDialect) { .... }protected String getDialectUri(String clientType, boolean claimMappingDefined) { .... }/** * Added method to retrieve claims from external sources. This results will be merged to the local claims when * returning final claim list, to be added to the SAML response, that is sent back to the SP. * * @param authenticatedUser : The user for whom we require claim values * @return */ private Map<String, String> handleExternalClaims(String authenticatedUser) throws FrameworkException { Map<String, String> externalClaims = new HashMap<String, String>(); externalClaims.put("http://pushpalanka.org/claims/keplerNumber","E90836W19881010"); externalClaims.put("http://pushpalanka.org/claims/status","active"); return externalClaims; } }Drop the compiled OSGI bundle at IS_HOME/repository/components/dropins. (We developed this as a OSGI bundle as we need to get local claims as well using RealmService. You can find the complete bundle and source code here) Point WSO2 Identity Server to use the new custom implementation we have.In IS_HOME/repository/conf/security/application­authentication.xml configure the new handler name. (in ‘ApplicationAuthentication.Extensions.ClaimHandler’ element.)    <ClaimHandler>com.wso2.sample.claim.handler.CustomClaimHandler</ClaimHandler> Now if look at the generated SAML Response, we will see the external attributes added. Cheers! [1] – https://docs.wso2.com/display/IS500/Adding+a+Service+ProviderReference: Adding Custom Claims to the SAML Response – (How to Write a Custom Claim Handler for WSO2 Identity Server) from our JCG partner Pushpalanka at the Pushpalanka’s Blog blog....

The lepidopterist’s curse: Playing with java.time

Pop quiz: What will be the output of this little program?                     public class DateFun { public static void main(String[] args) { long hours = getHoursOfDay(LocalDate.now(), ZoneId.systemDefault()); System.out.println(hours); } private static long getHoursOfDay(LocalDate date, ZoneId zoneId) { ZonedDateTime startOfDay = date.atStartOfDay(zoneId); Duration duration = Duration.between(startOfDay, startOfDay.plusDays(1)); return duration.toHours(); } } The answer is, like with most interesting questions, “it depends”. How can it depend? Well, let’s try a few examples:getHoursOfDay(LocalDate.of(2014, 7, 15), ZoneId.of("Asia/Colombo")) returns 24. As expected getHoursOfDay(LocalDate.of(2014, 7, 15), ZoneId.of("Europe/Oslo")) also returns 24. But here comes a funny version: getHoursOfDay(LocalDate.of(2014, 3, 30), ZoneId.of("Europe/Oslo")) returns 23! This is daylight saving time. Similarly: getHoursOfDay(LocalDate.of(2014, 10, 26), ZoneId.of("Europe/Oslo")) also returns 25 And of course, down under, everything is upside down: getHoursOfDay(LocalDate.of(2014, 10, 5), ZoneId.of("Australia/Melbourne")) gives 23. Except, of course, in Queensland: getHoursOfDay(LocalDate.of(2014, 10, 5), ZoneId.of("Australia/Queensland")) => 24.Daylight saving hours: The bane of programmers! Daylight saving hours were instituted with the stated purpose of improving worker productivity by providing more working hours with light. Numerous studies have failed to prove that it works as intended. Instead, when I examined the history of daylight saving hours in Norway, it turns out that it was lobbied by a golfer and a butterfly collector (“lepidopterist”) so that they could better pursue their hobbies after working hours. Thus the name of this blog post. Most of the time, you can ignore daylight saving hours. But when you can’t, it can really bite you in the behind. For example: What does the hour by hour production of a power plan look like on the day that changes from daylight saving hours to standard time? Another example given to me by a colleague: TV schedules. It turns out that some TV channels just can’t be bothered to show programming during the extra hour in the fall. Or they will show the same hour of programming twice. The Joda-Time API and now, the Java 8 time API java.time can help. If you use it correctly. Here is the code to display a table of values per hour: void displayHourlyTable(LocalDate date, ZoneId zoneId) { ZonedDateTime startOfDay = date.atStartOfDay(zoneId); ZonedDateTime end = startOfDay.plusDays(1); for (ZonedDateTime current = startOfDay; current.isBefore(end); current = current.plusHours(1)) { System.out.println(current.toLocalTime() + ": " + current.toInstant()); } } Given 2014/10/26 and Oslo, this prints: 00:00: 2014-10-25T22:00:00Z 01:00: 2014-10-25T23:00:00Z 02:00: 2014-10-26T00:00:00Z 02:00: 2014-10-26T01:00:00Z 03:00: 2014-10-26T02:00:00Z .... And on 2014/3/30, it prints: 00:00: 2014-03-29T23:00:00Z 01:00: 2014-03-30T00:00:00Z 03:00: 2014-03-30T01:00:00Z 04:00: 2014-03-30T02:00:00Z .... So, if you ever find yourself writing code like this: for (int hour=0; hour<24; hour++) doSomething(midnight.plusHours(hour)); you may want to reconsider! This code will (probably) break twice a year. At the face of it, time is an easy concept. When you start looking into the details, there’s a reason that the java.time library contains 20 classes (if you don’t count the subpackages). When used correctly, time calculations are simple. When used incorrectly, time calculations look simple, but contain subtle bugs. Next time, perhaps I should ruminate on the finer points of Week Numbers.Reference: The lepidopterist’s curse: Playing with java.time from our JCG partner Johannes Brodwall at the Thinking Inside a Bigger Box blog....

Java private, protected, public and default

You are a Java programmer, so you know what I am talking about. public modifiers make a method or field accessible from anywhere in the application. That is the simple part. But can you tell me the difference between protected and package private? (Hint: package private is the protection of a method or a field when you do not write any access modifier in front of it. Be aware! I lie!) My interview experience is that many do not know. Do I consider that as a no go for a Java developer? Not really. You may still be a good Java developer even if you do not know that. Perhaps now you will look it up somewhere. Perhaps the Java spec is a good document to start. I’ll tell you something more interesting.   Literally, none of the candidates know what private is. And you, reading this article, also do not know. Ok, this is very provocative. You may be one of the few who happen to fill his brain with such a useless information and you may even have read the Java specification. Most Java programmers think that private methods and fields are accessible only from within the class. Some even think that only from within the object instance. They believe that: public class PrivateAccessOtherObject { public PrivateAccessOtherObject(int i) { this.i = i; } private int i; void copyiTo(PrivateAccessOtherObject other){ other.i = i; } } is not possible. (It is.) So what is private? The recent JLS says that A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. The example in the Java specification is not the best describing the rule. Perhaps that is just a simple example. Something like this may be better explaining the concept: public class PrivateFieldsContainingClass { private static class NestedClass { private int i; } private NestedClass nestedClassInstance = new NestedClass(); void set(int i) { nestedClassInstance.i = i; } int get() { return nestedClassInstance.i; } } The field i is accessible from the enclosing class as well as from inside the NestedClass. This example is also simple but more to the point that the specification example misses. Is there any real use of this possibility? Not really. Bonus question: why did I say I was lying?Reference: Java private, protected, public and default from our JCG partner Peter Verhas at the Java Deep blog....

Avoiding Null Checks In Java

One of the worst nightmares for java developers ( from junior to experts ) is null object reference checking. I’m pretty sure you have seen several times code like this:                   public void addAddressToCustomer(Customer customer, Address newAddress){ if ( cutomer == null || newAddress == null) return; if ( customer.getAddresses() == null ){ customer.setAddresses ( new ArrayList<>()); } customer.addAddress(newAddress); } Personally I hate writing code for null check. In this post I will list some of the things that have worked well for me and are based on my personal experience in production environments and systems.Stop checking for null objects in all layers. Limit the checks only on the upper layers such as UI layer, presentation layer or the layer of your API controllers. In other words ensure that no null objects are passed from upper layers to the business logic layer.  For instance if you are developing a standard web application using Spring annotations then you’re probably have some classes annotated with @Repository , @Service , @Controller. Controllers are responsible for receiving client’s data and pass it to the @Service class for processing. It’s their responsibility to ensure that NO null objects are passed to the service layer. Service classes and below should not be null-safe. If they’re invoked with nulls then they should throw NPE to warn developers that they should fix this error. Remember that NPE is not a user error but a developer’s error and it should be always avoided.  Do the same with user inputs that comes from html forms or other user interface input.If you follow the above approach you won’t be tempted anymore to write business logic based on the fact that an object is null or not. Null objects should not be used to decide the behavior of your system. They are exceptional values and should be treated like errors and not valid business logic state.When returning a list from a method, always return an empty list instead of null. This will allow clients to iterate the list without checking for nulls. Iterating an empty list is totally accepted and will just do nothing, whereas iterating a null list will throw a NPE.In your persistent layer when you search for a specific object (i.e. using its identifier) and it’s not found then a very common approach is to return a null object. Well, this will make all clients to manually check for this null case. In this case you have two alternatives. Either throw a run-time exception (i.e. ObjectNotFoundException ) or return an empty Object. I have used both of these options and my suggestion is to evaluate them depending on the overall architecture of your system and the tools / frameworks used.When comparing a strings always put first the string that is less possible to be null so instead of:customer.getAddress().getStreet().equals("Times Square") prefer: "Times Square".equals(customer.getAddress().getStreet())If you’re using or planning to use Java8 then the new Optional class is here for you. Check this article that clearly explains the use of Optional.Next time you’re going to write some null check code try to think a little and decide if it’s redundant or not.Reference: Avoiding Null Checks In Java from our JCG partner Patroklos Papapetrou at the Only Software matters blog....

Avoiding Many If Blocks For Validation Checking

There are cases that we want to validate input data before we send them to business logic layer for processing, computations etc. This validation, in most cases, is done in isolation or it might include some cross-checking with external data or other inputs. Take a look at the following example that validates user input for registration data.               public void register(String email, String name, int age) { String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern pattern = Pattern.compile(EMAIL_PATTERN); List<String> forbiddenDomains = Arrays.asList("domain1", "domain2"); if ( email == null || email.trim().equals("")){ throw new IllegalArgumentException("Email should not be empty!"); } if ( !pattern.matcher(email).matches()) { throw new IllegalArgumentException("Email is not a valid email!"); } if ( forbiddenDomains.contains(email)){ throw new IllegalArgumentException("Email belongs to a forbidden email"); } if ( name == null || name.trim().equals("")){ throw new IllegalArgumentException("Name should not be empty!"); } if ( !name.matches("[a-zA-Z]+")){ throw new IllegalArgumentException("Name should contain only characters"); } if ( age <= 18){ throw new IllegalArgumentException("Age should be greater than 18"); } // More code to do the actual registration } The cyclomatic complexity of this method is really high and it might get worse if there are more fields to validate or if we add the actual business logic. Of course we can split the code in two private methods ( validate, doRegister ) but the problem with several if blocks will be moved to the private methods. Besides this method is doing more than one thing and is hard to test. When I ask junior developers to refactor this code and make it more readable, testable and maintainable they look at me like an alien :”How am I supposed to make it simpler. How can I replace these if blocks?” Well here’s a solution that works fine, honors the Single Responsibility Pattern and makes the code easier to read. To better understand the solution, think each of these if blocks as a validation rule. Now it’s time to model these rules. First create an interface with one method. In Java 8 terms, it’s called a functional interface, like the following. public interface RegistrationRule{ void validate(); } Now it’s time to transform each validation check to a registration rule. But before we do that we need to address a small issue. Our interface implementation should be able to handle registration data but as you see we have different types of data. So what we need here is to encapsulate registration data in a single object like this : public class RegistrationData{ private String name; private String email; private int age; // Setters - Getters to follow } Now we can improve our functional interface: public interface RegistrationRule{ void validate(RegistrationData regData); }and start writing our rule set. For instance let’s try to implement the email validation. public class EmailValidatationRule implements RegistrationRule{ private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private final Pattern pattern = Pattern.compile(EMAIL_PATTERN); @Override public void validate(RegistrationData regData) { if ( !pattern.matcher(regData.email).matches()) { throw new IllegalArgumentException("Email is not a valid email!"); } } It’s clear that we have isolated in the above class the email validation. We can do the same for all rules of our initial implementation. Now we can re-write our register method to use the validation rules. List<RegistrationRule> rules = new ArrayList<>(); rules.add(new EmailValidatationRule()); rules.add(new EmailEmptinessRule()); rules.add(new ForbiddenEmailDomainsRule()); rules.add(new NameEmptinessRule()); rules.add(new AlphabeticNameRule()); for ( RegistrationRule rule : rules){ rule.validate(regData); } To make it even better we can create a Rules class using the Factory pattern and a static method get() that will return the list of rules. And our final implementation will look like this for ( RegistrationRule rule : Rules.get()){ rule.validate(regData); } Comparing the initial version of our register method to the final one leaves room for doubts. Our new version is more compact, more readable and of course more testable. The actual checks have been moved to separate classes (which are easy to test also) and all methods do only one thing (try to always keep that in mind).Reference: Avoiding Many If Blocks For Validation Checking from our JCG partner Patroklos Papapetrou at the Only Software matters blog....

Spring 4.1 and Java 8: java.util.Optional

As of Spring 4.1 Java 8’s java.util.Optional, a container object which may or may not contain a non-null value, is supported with @RequestParam, @RequestHeader and @MatrixVariable. While using Java 8’s java.util.Optional you make sure your parameters are never null.     Request Params In this example we will bind java.time.LocalDate as java.util.Optional using @RequestParam: @RestController @RequestMapping("o") public class SampleController {@RequestMapping(value = "r", produces = "text/plain") public String requestParamAsOptional( @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "ld") Optional<LocalDate> localDate) {StringBuilder result = new StringBuilder("ld: "); localDate.ifPresent(value -> result.append(value.toString())); return result.toString(); } } Prior to Spring 4.1, we would get an exception that no matching editors or conversion strategy was found. As of Spring 4.1, this is no more an issue. To verify the binding works properly, we may create a simple integration test: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration public class SampleSomeControllerTest {@Autowired private WebApplicationContext wac; private MockMvc mockMvc;@Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); }// ...} In the first test, we will check if the binding works properly and if the proper result is returned: @Test public void bindsNonNullLocalDateAsRequestParam() throws Exception { mockMvc.perform(get("/o/r").param("ld", "2020-01-01")) .andExpect(content().string("ld: 2020-01-01")); } In the next test, we will not pass ld parameter: @Test public void bindsNoLocalDateAsRequestParam() throws Exception { mockMvc.perform(get("/o/r")) .andExpect(content().string("ld: ")); } Both tests should be green! Request Headers Similarly, we can bind @RequestHeader to java.util.Optional: @RequestMapping(value = "h", produces = "text/plain") public String requestHeaderAsOptional( @RequestHeader(value = "Custom-Header") Optional<String> header) {StringBuilder result = new StringBuilder("Custom-Header: "); header.ifPresent(value -> result.append(value));return result.toString(); } And the tests: @Test public void bindsNonNullCustomHeader() throws Exception { mockMvc.perform(get("/o/h").header("Custom-Header", "Value")) .andExpect(content().string("Custom-Header: Value")); }@Test public void noCustomHeaderGiven() throws Exception { mockMvc.perform(get("/o/h").header("Custom-Header", "")) .andExpect(content().string("Custom-Header: ")); } Matrix Variables Introduced in Spring 3.2 @MatrixVariable annotation indicates that a method parameter should be bound to a name-value pair within a path segment: @RequestMapping(value = "m/{id}", produces = "text/plain") public String execute(@PathVariable Integer id, @MatrixVariable Optional<Integer> p, @MatrixVariable Optional<Integer> q) {StringBuilder result = new StringBuilder(); result.append("p: "); p.ifPresent(value -> result.append(value)); result.append(", q: "); q.ifPresent(value -> result.append(value));return result.toString(); } The above method can be called via /o/m/42;p=4;q=2 url. Let’s create a test for that: @Test public void bindsNonNullMatrixVariables() throws Exception { mockMvc.perform(get("/o/m/42;p=4;q=2")) .andExpect(content().string("p: 4, q: 2")); } Unfortunatelly, the test will fail, because support for @MatrixVariable annotation is disabled by default in Spring MVC. In order to enable it we need to tweak the configuration and set the removeSemicolonContent property of RequestMappingHandlerMapping to false. By default it is set to true. I have done with WebMvcConfigurerAdapter like below: @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); } } And now all tests passes! Please find the source code for this article here: https://github.com/kolorobot/spring41-samplesReference: Spring 4.1 and Java 8: java.util.Optional from our JCG partner Rafal Borowiec at the Codeleak.pl blog....

How designing for the cloud would improve your service implementation

Cloud platforms come with a variety of options and constraints certainly driven by infrastructure and business needs which indeed diversify their pricing plans and customer adoption as well. But often they also have an implicit value: designing with certain constraints in mind would facilitate scaling and replication, would provide performance gains and increased revenues. Are constraints such as request timeout or limits on outbound traffic and datastore usage, so bad after all? However, when designing for your private hosting, you might skip or ignore few of them and miss an opportunity to improve your service design. Here are few points worth to consider:      Design for monetization: no matter which PaaS you would choose, it will always have constraints on network traffic, datastore connections, datastore space and so on, and that’s reasonable and obvious: they need to make a profit after all. When designing for the cloud you definitely need to face these constraints trying to minimize your expenses (review your data model, restrict required data, limit outbound traffic, adding cache mechanisms and so on), because you certainly want to increase as much as possible your monthly revenue. Designing for your private hosting you would not have taken so seriously some of these parameters perhaps, realizing later on their importance though.Design for performance: as part of the previous point, you might need to adapt your design to fit some cloud constraints and obtain a considerable performance gain which wasn’t directly linked to monetization (but it would impact it somehow after all). You need to limit your outbound traffic, your request time-out, the number of queries on your database, any long running process and so on: well, a bit of healthy pressure on these subjects would definitely not hurt your design.Design for latest technologies and standards: PaaS usually don’t support all existing technologies nor all frameworks/tools per technology, but they normally offer the most common ones, well known and widely used, because they obviously need to target a large community and facilitate your deploy (and their profit). These constraints may change your decision concerning build management, for instance, giving up on your well proven ant script and going for Maven on Heroku, or finally stop using a certain old-but-known library in favour of a more modern and effective one. That might have an impact on your roadmap though because of unexpected learning curves and you would not have faced this question on your nice private hosting, but it might be time to upgrade your competences while working on your project, soon or later you may appreciate that. And it could facilitate the integration of new team members in the future.Design for abstraction: the majority of PaaS would also require some platform/API dependency which would make your application cloud-platform dependent, something you would definitely try to avoid. Adding further layers of abstraction may solve the issue: you may use Memcache or Big table on GAE, for instance, but your service shouldn’t know that if you really want to keep a smooth portability. It’s an extra effort indeed which may affect the decision of choosing a target Paas rather than another, but that’s worth in case of future moves. You would probably not waste time and energy on your more open remote or private hosting, but you may end up later on in complex refactorings and wonder why a simple and clean abstraction wasn’t part of your initial design.Conclusion While you would reasonably ignore cloud constraints when designing for your private hosting, you might gain a quick added value just keeping in mind few of their constraints and challenge your design against them: how would your design react? Would it be easy to deploy your application elsewhere? Would your monetization improve adapting your design to any of them? The exercise is worth the effort as long as it doesn’t sound completely artificial and you do see some potential added values. There are plenty of non functional requirements you might just have left out and possibly you might also consider to use a cloud platform for your final deploy. Pick up two or three of the most used ones (AWS, GAE, Openshift, Heroku, Cloudbees are worth to mention, but they are not the only ones) and dare your design for an hypothetical deploy.Reference: How designing for the cloud would improve your service implementation from our JCG partner Antonio Di Matteo at the Refactoring Ideas blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: