Featured FREE Whitepapers

What's New Here?

java-logo

Java Coding Conventions considered harmful

There is an official Code Conventions for the Java Programming Language guide published on Oracle site. You would expect this 20+ pages document to be the most complete, comprehensive and authoritative source of good practices, hints and tips with regards to the Java language. But once you start to read it, disappointment followed by frustration and anger increases. I would like to point out the most obvious mistakes, bad practices, poor and outdated advices given in this guide. In case you are a Java beginner, just forget about this tutorial and look for better and more up-to-date reference materials. Let the horror begin!2.2 Common File Names:GNUmakefile The preferred name for makefiles. We use gnumake to build our software.  gnumake to build Java projects? ant is considered old-school, so is maven. Who uses maketo build WARs, JARs, generate JavaDocs…?3.1.1 Beginning Comments: All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice: Putting a class name in the comment starting a file? What if I change my mind and rename the class later? And what should that ‘ date‘ represent? Some people use various placeholders to insert last modification time of a file automatically by version control system. Well, VCS is there to tell you when the file was created or last modified – and modifying the same line over and over again makes merging a huge pain.4 – Indentation: Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).Probably the most counterintuitive part of the document. Some prefer spaces, others (including me) – tabs. A matter of taste and team arrangements. But this guide suggests to use both and replace spaces with tabs, sometimes. It’s ‘ unspecified‘. My advice: use tabs and let each developer configure his IDE to have as big or as small indentations as desired. 4.1 Line Length: Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools. 80 characters? My laptop can easily fit three times as much. Strive for 120-140 characters in one line, but don’t use hard-wraps. Personally I just display vertical margin and the right line length is dictated by readability. BTW here are few examples of classes from various libraries and frameworks:SQLIntegrityConstraintViolationException (JDK 7, 40 characters) AbstractInterruptibleBatchPreparedStatementSetter (Spring framework, 50 characters) AbstractDataSourceBasedMultiTenantConnectionProviderImpl (Hibernate, 56 characters) PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails (Spring Security, 58 characters)And we are suppose to fit whole line in 80 characters? 5.1.2 Single-Line Comments: if (condition) {/* Handle the condition. */ ... } Just in case the code is not self-descriptive enough, I suggest even better comment: if (condition) {/* This block is executed if condition == true. */ ... } 5.1.3 Trailing Comments: if (a == 2) { return TRUE; /* special case */ } else { return isPrime(a); /* works only for odd a */ } Did you mean (and don’t tell me it’s less readable, even without comments)? return a == 2 || isPrime(a); 6.1 Number Per Line: int level; // indentation level int size; // size of table Why use descriptive variable names, when we have comments! Consider this instead: int indentationLevel; int tableSize; Later in that section: In absolutely no case should variables and functions be declared on the same line. Example: long dbaddr, getDbaddr(); // WRONG! Sure it’s wrong, it doesn’t even compile. I’m surprised that ‘ don’t put spaces in variable names ‘ is not mentioned as a good practice… 6.3 Placement: Put declarations only at the beginning of blocks. [...] Don’t wait to declare variables until their first use; it can confuse the unwary programmer [...] This is how the coding conventions want you to write your code: int min; //inclusive int max; //exclusive int distance; List<String> list; //one per each itemmin = findMin(); max = findMax(); distance = max - min; list = new ArrayList<>(distance); //... And this is how it should be written to avoid confusion: final int minInclusive = findMin(); final int maxExclusive = findMax(); final int distance = maxExclusive - minInclusive; final List<String> listOfItems = new ArrayList<>(distance); //... Besides we can finally ( nomen est omen) use final keyword. Later in this section code sample is shown with class fields missing private modifier (default, package private access). Package private field? 7.3 return Statements: return (size ? size : defaultSize); Maybe you haven’t noticed, but from the context we can tell that both size and defaultSize are of boolean type. That’s right, size and defaultSize can be either true or false (!) How counterintuitive is that! From such a document I would expect not only syntactical correctness, but also meaningful code and good practices! Moreover, the expression can be greatly simplified, step-by-step: size ? size : defaultSize size ? true : defaultSize size || defaultSize 7.5 for Statements: An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form: for (initialization; condition; update);‘ empty for statement‘? Why would you ever use an empty for statement? This is confusing and should be avoided, not encouraged and described in the official language guide. Bonus quiz: what’s the purpose of this code in C? while(*dst++ = *src++); I believe every computer programmer should understand the code snippet above. Even if you program in Ruby or TSQL. 7.8 switch Statements: Every time a case falls through (doesn’t include a break statement), add a comment where thebreak statement would normally be.I understand the intentions, but the approach is wrong. Instead of documenting unexpected and error-prone code-fragments, just avoid them. Don’t depend on fall through, don’t use it at all. 8.1 Blank Lines: One blank line should always be used in the following circumstances: [...]Between the local variables in a method and its first statement Before a block [...] or single-line [...] comment Between logical sections inside a method to improve readabilityLooks like the authors suggest using blank lines to separate  ‘logical sections of a method‘. Well, I call these sections: ‘ methods‘. Don’t group statements inside methods in blocks, comment them and separate from each other. Instead extract them into separate, well named methods! Placing a blank line between variable declarations and the first statement sounds like taken from a C language book. 8.2 Blank Spaces:All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (‘++‘), and decrement (‘--‘) from their operands. Example:[...] while (d++ = s++) { n++; } This doesn’t even compile in Java… 9 – Naming Conventions (only in PDF version): char *cp; A good name for a char pointer in Java is cp. Wait, WHAT? char pointer in Java? 10.1 Providing Access to Instance and Class Variables:Don’t make any instance or class variable public without good reason. Really, really good reason! Did I ever used public field? 10.4 Variable Assignments: if (c++ = d++) { // AVOID! (Java disallows) ... } Great advice: please avoid using constructs that do not even compile in Java. This makes our lives so much easier! 10.5.2 Returning Values: if (booleanExpression) { return true; } else { return false; } should instead be written asreturn booleanExpression; Holy cow, I AGREE! Summary It’s not that the official Code Conventions for the Java Programming Language are completely wrong. They are just outdated and obsolete. In the second decade of the XXI century we have better hardware, deeper  understanding of code quality and more modern sources of wisdom. Code Conventions… were last published in 1999, they are heavily inspired by C language, unaware of billions of lines of code yet to be written by millions of developers. Code conventions should emerge over time, just like design patterns, rather than be given explicitly. So please, don’t quote or follow advices from official guide ever again. Reference: Java Coding Conventions considered harmful from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog....
whitesource-logo

Open Source Legal Blues: Do You Comply?

Understanding and Reducing Open Source License Risks In today’s business climate, using Open Source Software (OSS) components as part of the development of new products is imperative.  At the same time, the risks of using OSS improperly are enormous. OSS usage introduces legal, business and technical risks. Legally, failure to comply with OSS licensing requirements may result in penalties and other costs. In some cases, companies may even be forced to remove their software from the market. From a business perspective, due diligence processes for M&A and investments require a thorough audit of all OSS components, and deals have been aborted due to tainted IP and expensive licensing obligations. In addition, some resellers and even enterprise customers have started to enforce OSS policies, and to demand transparency from software vendors. From a technical perspective, OSS security vulnerabilities may call for intruders who can review the publicly available code searching for holes. Thus, it is important to maintain good visibility into your OSS usage, and to make informed decisions in real time. Most companies are addressing OSS challenges using spreadsheets and other static documents. This leads to missing and out of date information, lack of collaboration, and no clear way to evaluate risk. Some commercial tools are available but require companies to exert substantial effort to track and validate OSS. With these tools, much of the compliance work is done near major and high risk events such as M&A, OEM deals, and new version releases. White Source, the leading SaaS Open Source Lifecycle Management platform, introduces a new approach. White Source provides a comprehensive, yet affordable, solution for companies that need to manage their open source assets and ensure license compliance. White Source SaaS service is easy to use, requires very little effort from developers and is always up-to-date.With White Source, new open source components are automatically detected when first used, and classified by their license type and risk profile. This allows the organization to immediately address the respective risks and license requirements, rather than wait until release time, thereby risking substantial development effort, and unnecessary delays.White Source integrates seamlessly and can automatically enforce organizational open source policy with leading development tools such as Apache maven, Apache Ant, Jenkins, JetBrains TeamCity, RedHat OpenShift, CloudBees and JFrog Artifactory. White Source is hosting a free webinar on November 13th, 10am EST titled “Open Source Legal Blues: Do You Comply?” The webinar will feature renowned IP legal expert Haim Ravia, and White Source CEO Rami Sass.The session will cover:Open source legal, business, and technical risks. How to effectively manage the open source adoption process, review procedures, and compliance requirements. How to do so without impacting development and release schedules, and without spending a small fortune.Register Now  ...
spring-interview-questions-answers

Spring Constructor Injection and Argument names

At runtime, java classes do not retain the name of the constructor or method parameters, unless classes are compiled with debug options on.This has some interesting implications for Spring Constructor Injection.Consider the following simple class    package dbg; public class Person {private final String first; private final String last; private final Address address;public Person(String first, String last, Address address){ this.first = first; this.last = last; this.address = address; }public String getFirst() { return first; }public String getLast() { return last; }public Address getAddress() { return address; } }and a sample Spring bean configuration xml file:<bean name='address1' class='dbg.Address' p:street1='street1' p:street2='street1' p:state='state1'/> <bean name='person1' class='dbg.Person' c:address-ref='address1' c:last='Last1' c:first='First1' ></bean> <bean name='person2' class='dbg.Person' c:first='First2' c:address-ref='address1' c:last='Last2' ></bean>Here I am using the c namespace for constructor injection. This fails with the exception that the argument types are ambiguous – this is because the first argument is a String and since its runtime representation does not have the argument name present, Spring cannot determine if it should be substituted for the first name or last. There are a couple of fixes possible for this scenario: 1. To use index based constructor injection, the drawback though is that it is very verbose:<bean name='person1' class='dbg.Person' > <constructor-arg value='First1'></constructor-arg> <constructor-arg value='Last1'></constructor-arg> <constructor-arg ref='address1'></constructor-arg> </bean> <bean name='person2' class='dbg.Person' > <constructor-arg value='First2'></constructor-arg> <constructor-arg value='Last2'></constructor-arg> <constructor-arg ref='address1'></constructor-arg> </bean>2. To compile with debug symbols on, this can be done by passing a -g or -g:var flag to the java compiler – this will ensure that the parameter names are preserved in the class file and the original concise bean configuration with c namespace will work. 3. A neat fix is to annotate the constructor with @ConstructorProperties which basically provides the argument names to Spring:public class Person {private final String first; private final String last; private final Address address;@ConstructorProperties({'first','last','address'}) public Person(String first, String last, Address address){ this.first = first; this.last = last; this.address = address; }This works with or without debug options turned on. 4. Probably the best fix of all is to simply use @Configuration to define the beans:@Configuration public static class TestConfiguration{@Bean public Address address1(){ return new Address(); } @Bean public Person person1(){ return new Person('First1', 'Last1', address1()); } @Bean public Person person2(){ return new Person('First2', 'Last2', address1()); }} Reference: Spring Constructor Injection and Argument names from our JCG partner Biju Kunjummen at the all and sundry blog. ...
groovy-logo

Grails: Autodiscovery of JPA-annotated domain classes

There are some issues to be fixed with the support for adding JPA annotations (for example @Entity) to Groovy classes in grails-app/domain in 2.0. This is due to the changes made to adding most GORM methods to the domain class bytecode with AST transformations instead of adding them to the metaclass at runtime with metaprogramming. There is a workaround – put the classes in src/groovy (or write them in Java and put them in src/java). This adds a maintenance headache though because by being in grails-app/domain the classes are automatically discovered, but there’s no scanning of src/groovy or src/java for annotated classes so they must be explicitly listed in grails-app/conf/hibernate/hibernate.cfg.xml. We do support something similar with the ability to annotate Groovy and Java classes with Spring bean annotations like @Component and there is an optional property grails.spring.bean.packages in Config.groovy that can contain one or more packages names to search. We configure a Spring scanner that looks for annotated classes and automatically registers them as beans. So that’s what we need for JPA-annotated src/groovy and src/java classes. It turns out that there is a Spring class that does this, org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean. It extends the standard SessionFactory factory bean class org.springframework.orm.hibernate3.LocalSessionFactoryBean and adds support for an explicit list of class names to use and also a list of packages to scan. Unfortunately the Grails factory bean class org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean also extends LocalSessionFactoryBean so if you configure your application to use AnnotationSessionFactoryBean you’ll lose a lot of important functionality from ConfigurableLocalSessionFactoryBean. So here’s a subclass of ConfigurableLocalSessionFactoryBean that borrows the useful annotation support from AnnotationSessionFactoryBean and can be used in a Grails application: package com.burtbeckwith.grails.jpa;import java.io.IOException;import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.MappedSuperclass;import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean; import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.cfg.Configuration; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.ClassUtils;/** * Based on org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean. * @author Burt Beckwith */ public class AnnotationConfigurableLocalSessionFactoryBean extends ConfigurableLocalSessionFactoryBean implements ResourceLoaderAware {private static final String RESOURCE_PATTERN = '/**/*.class';private Class<?>[] annotatedClasses; private String[] annotatedPackages; private String[] packagesToScan;private TypeFilter[] entityTypeFilters = new TypeFilter[] { new AnnotationTypeFilter(Entity.class, false), new AnnotationTypeFilter(Embeddable.class, false), new AnnotationTypeFilter(MappedSuperclass.class, false), new AnnotationTypeFilter(org.hibernate.annotations.Entity.class, false)};private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();public AnnotationConfigurableLocalSessionFactoryBean() { setConfigurationClass(GrailsAnnotationConfiguration.class); }public void setAnnotatedClasses(Class<?>[] annotatedClasses) { this.annotatedClasses = annotatedClasses; }public void setAnnotatedPackages(String[] annotatedPackages) { this.annotatedPackages = annotatedPackages; }public void setPackagesToScan(String[] packagesToScan) { this.packagesToScan = packagesToScan; }public void setEntityTypeFilters(TypeFilter[] entityTypeFilters) { this.entityTypeFilters = entityTypeFilters; }public void setResourceLoader(ResourceLoader resourceLoader) { this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); }@Override protected void postProcessMappings(Configuration config) throws HibernateException { GrailsAnnotationConfiguration annConfig = (GrailsAnnotationConfiguration)config; if (annotatedClasses != null) { for (Class<?> annotatedClass : annotatedClasses) { annConfig.addAnnotatedClass(annotatedClass); } } if (annotatedPackages != null) { for (String annotatedPackage : annotatedPackages) { annConfig.addPackage(annotatedPackage); } } scanPackages(annConfig); }protected void scanPackages(GrailsAnnotationConfiguration config) { if (packagesToScan == null) { return; }try { for (String pkg : packagesToScan) { logger.debug('Scanning package '' + pkg + '''); String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN; Resource[] resources = resourcePatternResolver.getResources(pattern); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); if (matchesFilter(reader, readerFactory)) { config.addAnnotatedClass(resourcePatternResolver.getClassLoader().loadClass(className)); logger.debug('Adding annotated class '' + className + '''); } } } } } catch (IOException ex) { throw new MappingException('Failed to scan classpath for unlisted classes', ex); } catch (ClassNotFoundException ex) { throw new MappingException('Failed to load annotated classes from classpath', ex); } }private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { if (entityTypeFilters != null) { for (TypeFilter filter : entityTypeFilters) { if (filter.match(reader, readerFactory)) { return true; } } } return false; } } You can replace the Grails SessionFactory bean in your application’s grails-app/conf/spring/resources.groovy by using the same name as the one Grails registers: import com.burtbeckwith.grails.jpa.AnnotationConfigurableLocalSessionFactoryBeanbeans = { sessionFactory(AnnotationConfigurableLocalSessionFactoryBean) { bean -> bean.parent = 'abstractSessionFactoryBeanConfig' packagesToScan = ['com.mycompany.myapp.entity'] } } Here I’ve listed one package name in the packagesToScan property but you can list as many as you want. You can also explicitly list classes with the annotatedClasses property. Note that this is for the “default” DataSource; if you’re using multiple datasources you will need to do this for each one. So this means we can define this class in src/groovy/com/mycompany/myapp/entity/Person.groovy: package com.mycompany.myapp.entityimport javax.persistence.Column import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id import javax.persistence.Version@Entity class Person {@Id @GeneratedValue Long id@Version @Column(nullable=false) Long version@Column(name='first', nullable=false) String firstName@Column(name='last', nullable=false) String lastName@Column(nullable=true) String initial@Column(nullable=false, unique=true, length=200) String email } It will be detected as a domain class and if you run the schema-export script the table DDL will be there in target/ddl.sql. There are a few issues to be aware of however, mostly around constraints. You can’t define a constraints or mapping block in the class – they will be ignored. The mappings that you would have added just need to go in the annotations. For example I have overridden the default names for the firstName and lastName properties in the example above. But nullable=true is the default for JPA and it’s the opposite in Grails – properties are required by default. So while the annotations will affect the database schema, Grails doesn’t use the constraints from the annotations and you will get a validation error for this class if you fail to provide a value for the initial property. You can address this by creating a constraints file in src/java; see the docs for more details. So in this case I would create src/java/com/mycompany/myapp/entity/PersonConstraints.groovy with a non-static constraints property, e.g. constraints = { initial(nullable: true) email unique: true, length: 200) } This way the Grails constraints and the database constraints are in sync; without this I would be able to create an instance of the domain class that has an email with more than 200 characters and it would validate, but cause a database constraint exception when inserting the row. This also has the benefit of letting you use the Grails constraints that don’t correspond to a JPA constraint such as email and blank.   Reference: Autodiscovery of JPA-annotated domain classes in Grails from our JCG partner Burt Beckwith at the An Army of Solipsists blog. ...
java-logo

Github Gists in Eclipse

I’d like to describe simple steps regarding integrating GitHub Gists in Eclipse. There are several sources which provoke me to do this:GitHub Mylyn connector for Eclipse EGit/GitHub/User Guide http://eclipse.github.comI’ve been using Eclipse Java EE destibution, Mylyn plugin has been already installed there:1. Install EGit plugin via Eclipse Marketplace:2. Install GitHub Mylyn Connector via Eclipse Marketplace:3. Open View ‘Task List’ and click ‘Add Repository':4. Add Mylyn Task repository – ‘GitHub Gists':5 .Then you should create Mylyn Query to fetch all Gists:6. You should get something like this:That’s it. PS. Please note I’ve excluded such common sense steps as providing credentials for your GitHub account.   Reference: Github Gists in Eclipse from our JCG partner Orest Ivasiv at the Knowledge Is Everything blog. ...
zk-logo

Advanced ZK: Asynchronous UI updates and background processing – part 2

Introduction In part 1 I showed how server push and threads can be used to execute background tasks in a ZK application. However, the simple example had a major flaw that makes it a bad approach for real-world applications: it starts a new thread for each background task. JDK5 introduced the ExecutorService class, which abstracts away the threading details, and gives us a nice interface which can be used to submit tasks for background processing. In this blog post I will describe the most important parts of creating a ZK app, which contains a background task that takes a string, and returns it in uppercase. The complete sample project is available at Github: https://github.com/Gekkio/blog/tree/master/2012/10/async-zk-part-2 1. Create an ExecutorService instance First we need an ExecutorService that we can use in our ZK code. In most cases we want a shared singleton instance, which could be configured and managed by dependency injection (e.g. Spring). It is very important to make sure that the ExecutorService is created only once, and it’s shut down properly with the application. In this sample project I will use a simple holder class, which manages the lifecycle of a single statically available ExecutorService instance. This holder must be configured as a listener in zk.xml. package sample;import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;import org.zkoss.zk.ui.WebApp; import org.zkoss.zk.ui.util.WebAppCleanup; import org.zkoss.zk.ui.util.WebAppInit;public class SampleExecutorHolder implements WebAppInit, WebAppCleanup {private static volatile ExecutorService executor;public static ExecutorService getExecutor() { return executor; }@Override public void cleanup(WebApp wapp) throws Exception { if (executor != null) { executor.shutdown(); System.out.println('ExecutorService shut down'); } }@Override public void init(WebApp wapp) throws Exception { executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); System.out.println('Initialized an ExecutorService'); }} Note that the thread pool is configured using a fixed size based on processors in the system. Proper thread pool sizing is very important, and depends on the type of tasks you intend to execute. The maximum number of threads is also the maximum amount of simultaneous concurrent tasks! 2. Write event classes that model the results of the background task We’ll use ZK server push to communicate the task results back to the UI, so the results must be modeled as ZK events. It’s always a good idea to create custom subclasses of Event instead of adding the results in the data parameter, because a custom class is more typesafe and can supports multiple fields. The first event class represents a status update that is sent while the task is still running. In this example it will contain the amount of characters in the input string. package sample;import org.zkoss.zk.ui.event.Event;public class FirstStepEvent extends Event {public final int amountOfCharacters;public FirstStepEvent(int amountOfCharacters) { super('onFirstStepCompleted', null); this.amountOfCharacters = amountOfCharacters; }} The second event class represents the fully completed task. In this example it contains the input string in upper case. package sample;import org.zkoss.zk.ui.event.Event;public class SecondStepEvent extends Event {public final String upperCaseResult;public SecondStepEvent(String upperCaseResult) { super('onSecondStepCompleted', null); this.upperCaseResult = upperCaseResult; }}   3. Write the task class The task class should have the following characteristics:It implements Runnable It takes all required input data as constructor arguments (the data should be immutable if possible!). This input data must be thread-safe, and generally should not include any ZK-related stuff (no components, sessions, etc.). For example, if you want to use a Textbox value as input, read the value in advance and don’t pass the Textbox itself as an argument. It takes a Desktop, and at least one EventListener as constructor arguments. They are needed for sending the results back to the UIIn this example the only input data is a string that will be used to compute the task results. package sample;import java.util.Locale;import org.zkoss.zk.ui.Desktop; import org.zkoss.zk.ui.DesktopUnavailableException; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener;public class SampleTask implements Runnable {private final String input; private final Desktop desktop; private final EventListener<Event> eventListener;@SuppressWarnings({ 'rawtypes', 'unchecked' }) public SampleTask(String input, Desktop desktop, EventListener eventListener) { this.input = input; this.desktop = desktop; this.eventListener = eventListener; }@Override public void run() { try { // Step 1 Thread.sleep(10000); Executions.schedule(desktop, eventListener, new FirstStepEvent(input.length()));// Step 2 Thread.sleep(10000); Executions.schedule(desktop, eventListener, new SecondStepEvent(input.toUpperCase(Locale.ENGLISH))); } catch (DesktopUnavailableException e) { System.err.println('Desktop is no longer available: ' + desktop); } catch (InterruptedException e) { } }} Note how all the constructor arguments are stored in private final fields, and how the input data is immutable (Strings are immutable in Java!). The task simulates long-running processing by using Thread.sleep, and submits a status event when the “processing” is half done. 4. Schedule tasks in ZK composers Using the task in composers is very simple. You only need to enable server push, and submit a new task instance to the executor. This automatically starts the task once a free background thread is available. desktop.enableServerPush(true); // Get the executor from somewhere executor = SampleExecutorHolder.getExecutor(); executor.execute(new SampleTask(input.getValue(), desktop, this)); In this sample the composer extends GenericForwardComposer, which implements EventListener, so it can itself handle the resulting task events. Both events are handled by methods that update the UI with status information. public void onFirstStepCompleted(FirstStepEvent event) { status.setValue('Task running: ' + event.amountOfCharacters + ' characters in input'); }public void onSecondStepCompleted(SecondStepEvent event) { status.setValue('Task finished: ' + event.upperCaseResult); }   Final words It’s quite easy to add robust support for long-running tasks in a ZK application by using this technique. The resulting code in ZK composers is very simple, because the results are passed using the typical Event/EventListener paradigm that is very common within ZK apps. The biggest dangers in this technique are thread-safety bugs, which can be very difficult to debug. It is absolutely crucial to fully understand the threads where every piece of code is executed, and ensure that all shared state is fully thread-safe. Using immutable input data, and immutable output events is usually enough to ensure safety as long as the background task itself doesn’t access other non-thread-safe resources. Some common mistakes are:Invoking thread-local dependent library methods in the background task (e.g. any method that seems to magically get the “current” value of some type). The background threads will not automatically contain the same thread-local values as servlet threads, so by default all these kind of methods will fail. For example Sessions.getCurrent(), Executions.getCurrent() in ZK, many Spring Security static methods. Passing non-thread-safe parameters to the background task. For example, passing a mutable List that might be modified by the composer while the task is running (always make copies of mutable collections!). Passing non-thread-safe result data in events. For example, passing a List in a result event, while the List will be modified later on in the task (always make copies of mutable collections!). Accessing non-thread-safe methods in the desktop. Even though you have access to the desktop in the background task, most desktop methods are not thread-safe. For example, calling desktop.isAlive() is not guaranteed to return the status correctly (at least in ZK 6.5 the method relies on non-volatile fields, so writes are not guaranteed to be visible in the background thread)  Reference: Advanced ZK: Asynchronous UI updates and background processing – part 2 from our JCG partner Joonas Javanainen at the Jawsy Solutions technical blog blog. ...
java-interview-questions-answers

Rest using Jersey – Complete Tutorial with JAXB, Exception Handling and Client Program

Recently I started working on a Restful web service project using Jersey API. There are some tutorials available online but I faced some issues with exception handling and I didn’t found anywhere complete project using JaxB and providing exception handling approach. So once I was able to create a Restful web service using Jersey API with exception handling and client program, I decided to write this tutorial to help everyone getting started with Jersey. Who Should Use This Tutorial This tutorial is intended for Java programmers who are interested in developing and deploying Restful Web Services using Jersey API and JaxB. Prerequisites The scope of this tutorial is to use Jersey API for creating Restful web services and invoking the web service using Java client program and testing web service using tool. Basic understanding of Java, Web Services, XML, Maven and any application server (JBoss/Tomcat) is required to understand the tutorial with ease. Softwares and Tools usedJDK version 1.6.0_37 Apache Maven 3.0.3 Mac OS X 10.8.2 JBoss 4.2.2 (You can use any application server like Tomcat, Glassfish etc.) Eclipse Indigo (Any Java IDE with Maven support)Creating Maven Project in Eclipse and Jersey Create a maven project in Eclipse and it will provide you with basic project structure. I have given GroupId as “JD” and artifactID as “my-jersey-project” but you can give anything you like. Once we complete the development of our project, it will look like below in the image.  Jersey Web service project explanation pom.xml: Project configuration details, note the jersey dependencies provided, other details are common for any maven project. <project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <groupId>JD</groupId> <artifactId>my-jersey-project</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging><dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.14</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.14</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.14</version> </dependency> </dependencies><build> <finalName>${artifactId}-${version}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.1-alpha-2</version> <configuration> <packagingExcludes> WEB-INF/lib/servlet-api-*.jar </packagingExcludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.0</version> <executions> <execution> <id>unpack</id> <phase>install</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>${groupId}</groupId> <artifactId>${artifactId}</artifactId> <version>${version}</version> <type>${packaging}</type> <overWrite>true</overWrite> <outputDirectory>${project.build.directory}/${artifactId}-${version}-exploded.${packaging}</outputDirectory> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> EmpRequest.java: Java Bean for the request object. The important thing to note here is @XmlRootElement annotation to map the class to an XML element. package com.jd.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = 'empRequest') public class EmpRequest { private int id; private String name;public int getId() { return id; }public void setId(int id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; } } EmpResponse.java: Java bean for the response object. package com.jd.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = 'empResponse') public class EmpResponse { private int id; private String name;public int getId() { return id; }public void setId(int id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }} ErrorResponse.java: Java Bean that will be send as response incase of exception. package com.jd.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = 'errorResponse') public class ErrorResponse {private String errorCode; private int errorId;public String getErrorCode() { return errorCode; }public void setErrorCode(String errorCode) { this.errorCode = errorCode; }public int getErrorId() { return errorId; }public void setErrorId(int errorId) { this.errorId = errorId; }} EmpNotFoundException.java: A normal exception class thrown in the web service. package com.jd.exception;public class EmpNotFoundException extends Exception {private static final long serialVersionUID = 4351720088030656859L; private int errorId;public int getErrorId() { return errorId; }public EmpNotFoundException(String msg, int errorId) { super(msg); this.errorId = errorId; }public EmpNotFoundException(String msg, Throwable cause) { super(msg, cause); } } jboss-web.xml: To define JBoss servlet context for the web service. <jboss-web> <context-root>jd</context-root> </jboss-web> web.xml: Deployment descriptor for the web service. So any request with URI “http://<HOST>:<POST>/jd/rest/*” will be processed by Jersey ServletContainer servlet. Important thing to note is the init-param value passed for “com.sun.jersey.config.property.packages”. This defines in which package jersey will look for the web service classes. This property must point to your resources classes. It also looks for the resource classes into the sub-packages. <?xml version='1.0' encoding='UTF-8'?> <web-app id='WebApp_ID' version='2.5' xmlns='http://java.sun.com/xml/ns/javaee' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd'><display-name>My Jersey Project</display-name><!-- Jersey Servlet configurations --> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.jd</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <!-- Jersey Servlet configurations --></web-app> EmpRouter.java: Resource class handling different kinds of request.@Path(“/emp”) – All the requests with URI http://<HOST>:<PORT>/jd/rest/emp/ will be processed by this resource class. @Path(“/getEmp”) – All the requests with URI http://<HOST>:<PORT>/jd/rest/emp/getEmp will be processed by this method. @POST – This annotation defines that the HTTP method used should be POST. Some other possible values are @GET, @PUT, @DELETE @Consumes(MediaType.APPLICATION_XML) – The method accepts XML element @Produces(MediaType.APPLICATION_XML) – The method returns XML elementpackage com.jd.router;import com.jd.exception.EmpNotFoundException; import com.jd.model.*;import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.JAXBElement;@Path('/emp') public class EmpRouter {@POST @Path('/getEmp') @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response getEmp(JAXBElement<EmpRequest> empRequest) throws EmpNotFoundException { EmpResponse empResponse = new EmpResponse(); if (empRequest.getValue().getId() == 1) { empResponse.setId(empRequest.getValue().getId()); empResponse.setName(empRequest.getValue().getName()); } else { throw new EmpNotFoundException('Wrong ID', empRequest.getValue() .getId()); } return Response.ok(empResponse).build(); } } EmpNotFoundExceptionMapper.java: Exception Mapper class that maps EmpNotFoundException to Response object. The class should have annotation @Provider. This class should be in the package provided for resource classes in web.xml. Implementation of toResponse() method generates the ErrorResponse object and set it as Entity in Response object with status as INTERNAL_SERVER_ERROR. package com.jd.exceptionmapper;import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider;import com.jd.exception.EmpNotFoundException; import com.jd.model.ErrorResponse;@Provider public class EmpNotFoundExceptionMapper implements ExceptionMapper<EmpNotFoundException> {public EmpNotFoundExceptionMapper() { }public Response toResponse( EmpNotFoundException empNotFoundException) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setErrorId(empNotFoundException.getErrorId()); errorResponse.setErrorCode(empNotFoundException.getMessage()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( errorResponse).type( MediaType.APPLICATION_XML).build();}} Our web service is ready, just build it to create the WAR file and deploy it in the application server. EmpClient.java: This is a sample java program through which are invoking our web service. We are using jersey client API to invoke the service and based on response status we are parsing response entity to EmpResponse or ErrorResponse class. package com.jd.client;import javax.ws.rs.core.MediaType;import com.jd.model.EmpRequest; import com.jd.model.EmpResponse; import com.jd.model.ErrorResponse; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource;public class EmpClient {/** * @param args */ public static void main(String[] args) { String uri = 'http://localhost:8080/jd/rest/emp/getEmp'; EmpRequest request = new EmpRequest(); //set id as 1 for OK response request.setId(2); request.setName('PK'); try{ Client client = Client.create(); WebResource r=client.resource(uri); ClientResponse response = r.type(MediaType.APPLICATION_XML).post(ClientResponse.class,request ); System.out.println(response.getStatus()); if(response.getStatus() == 200){ EmpResponse empResponse = response.getEntity(EmpResponse.class); System.out.println(empResponse.getId() + '::'+empResponse.getName()); }else{ ErrorResponse exc = response.getEntity(ErrorResponse.class); System.out.println(exc.getErrorCode()); System.out.println(exc.getErrorId()); } }catch(Exception e){ System.out.println(e.getMessage()); } }} I hope the tutorial is easy enough to follow and write your first Restful web service using Jersey. Please let me know if you face any issues or need further explanations.   Reference: Rest using Jersey – Complete Tutorial with JAXB, Exception Handling and Client Program from our JCG partner Pankaj Kumar at the Developer Recipes blog. ...
java-logo

Java 7: File Filtering using NIO.2 – Part 1

NIO.2 is a new API for I/O operations included in the JDK since Java 7. With this new API, you can perform the same operations performed with java.io plus a lot of great functionalities such as: Accessing file metadata and watching for directory changes, among others. Obviously, the java.io package is not going to disappear because of backward compatibility, but we are encouraged to start using NIO.2 for our new I/O requirements. In this post, we are going to see how easy it is to filter the contents of a directory using this API. There are 3 ways in order to do so, that’s why this post is Part1. What you need NetBeans 7+ or any other IDE that supports Java 7 JDK 7+ Filtering content of a directory is a common task in some applications and NIO.2 makes it really easy. The classes and Interfaces we are going to use are described next:java.nio.file.Path: Interface whose objects may represent files or directories in a file system. It’s like the java.io.File but in NIO.2. Whatever I/O operation you want to perform, you need an instance of this interface. java.nio.file.DirectoryStream: Interface whose objects iterate over the content of a directory. java.nio.file.Files: Class with static methods that operates on files, directories, etc.The way we are going to filter the contents of a directory is by using glob patterns, which are like regular expressions but simpler. The pattern is matched against the name of the files, directories, etc. That live inside the directory. This is important to remember, using this method you can only filter by the name of the file, directory, etc. For more information about globbing, check this wiki. Also, there is some documentation about globbing patterns in the Java Docs. So, let’s suppose that we have a directory called Images, and we need to iterate over the files inside this directory, but we only need the .png files. We have to follow this steps in order to do so:Obtain a java.nio.file.Path instance which points to the directory Images. Open a new java.nio.file.DirectoryStream using the java.nio.file.Files class and passing the directory and the pattern (*.png) as parameters. Iterate over the content of the directory using the java.nio.file.DirectoryStream instance.Next is the source code of a method that scans a directory using the pattern passed as parameter: //in a class.../** * Scans the directory using the glob pattern passed * as parameter. * @param folder directory to scan * @param pattern glob pattern (filter) */ private static void scan(String folder, String pattern) { //obtains the Images directory in the app directory Path dir = Paths.get(folder); //the Files class offers methods for validation if (!Files.exists(dir) || !Files.isDirectory(dir)) { System.out.println('No such directory!'); } //Try with resources... so nice! try (DirectoryStreamds = Files.newDirectoryStream(dir, pattern)) { //iterate over the content of the directory int count = 0; for (Path path : ds) { System.out.println(path.getFileName()); count++; } System.out.println(); System.out.printf('%d Files match the pattern' , count); } catch (IOException ex) { ex.printStackTrace(); } } Following is the result of the execution on my windows machine:And on my Linux virtual machine:That’s something I love from Java, Write once, run everywhere! I hope you enjoyed this post, there are more ways to filter the content of a directory and we’ll explore them in future posts. Click here to download the complete source code.   Reference: Java 7: File Filtering using NIO.2 – Part 1 from our JCG partner Alexis Lopez at the Java and ME blog. ...
software-development-2-logo

Introduction To REST Concepts

Introduction This post aims at demystifying the REST (Representational State Transfert) web design concepts. REST is based on a client server model. REST is a set of principles describing how standards can be used to develop web applications, for example. Its main purpose is to anticipate on common implementation issues and organize the relationship between logical clients and servers. You could call it a set of best practices! In practice, REST provides guidance on how to implement web application interfaces to the web. Typically, one says a web application is constructed in a REST-like way or not. REST is often associated (or implemented) with HTTP, but it could be implemented with other technologies too. REST is platform and language independent. Roy Fielding, the inventor of REST, says REST aims at achieving the following:Generality Of Interfaces – All web applications should implement their interfaces the same way. By sharing the same convention, other applications know how to call yours, and you know how to call theirs. Minimal learning curve for each new application. Independent Deployment of Components – Once an application and its REST interfaces have been implemented and deployed, one must be able to implement or re-implement, and deploy any REST interfaces without having to rewrite or modify existing ones. Encapsulate Legacy Systems – Existing applications which are not implemented in a REST-like way can be wrapped with REST interfaces, making them REST-like applications. Intermediary Components To Reduce Interaction Latency – For example, in order to handle traffic, it is common to distribute user/client requests to several physical servers (which is not to be confused with logical servers). This is transparent for users. Since REST uses interfaces, implementing or adding extra layered components, such as physical servers to handle a peak of client requests, is easy. Emphasizing The Scalability Of Component Interactions – This is complementary to the previous point. Enforce Security – Exchanging information over the Internet can be risky. Hackers can use it to twist the system. REST principles eliminate many of those risks.ConceptsResource – A logical resource is any concept (car, dog, user, invoice…) which can be addressed and referenced using a global identifier. Typically, each resource is accessible with a URI when implementing REST over HTTP (for example: http://www.mysite.com/invoice/34657). Server – A logical server is where resources are located, together with any corresponding data storage features. Such servers do not deal with end user interfaces (GUI). Client – Logical clients make requests to logical servers to perform operations on their resources. For example, a client can request the state of the resource, create a resource, update a resource, delete a resource, etc… Clients do not possess resources or corresponding data storage features. However, they deal with end user interfaces (GUI). Request and Responses – The interactions between client and servers is organized with requests from client to server, and responses to requests from server back to client. Requests can contain representations of the resource. Representation – A representation is a document representing the current status of a resource. It can also be the new desired status when a client makes a request to update a resource, for example.Principles Here are some principles applicable in REST-like applications:The state of a resource remains internal to the server, not the client – The client can request it, or update it with requests made to the server. No client context saved on the server between requests – The server must not store the status of a client. Otherwise, this would break the scalability objective of REST when reaching a couple million users. Remember that requests can be distributed to several physical servers, which could cause physical resource consumption issues. Client requests contain all information to service it – No matter which request is sent by a client to a server, it must be complete enough for the server to process it. Session states are stored on the client side – If necessary, any information about the status of the communication between a logical server and a logical client must be held on the client side. Multiple representations of a resource can coexist – The chosen format used to represent the state of a resource in requests and responses is free (XML, JSON…). Multiple formats can be used. Responses explicitly indicate their cacheability – When a server returns a response to a request, the information it contains may or may not be cached by the client. If not, the client should make new requests to obtain the latest status of a resource, for example. Code on Demand – This is an optional feature in REST. Clients can fetch some extra code from the server to enrich their functionalities. An example is Javascript.About session states, implementing a login logout (i.e., authentication) system between a physical server and a physical client requires saving session information on the server side. Otherwise, if it were saved on the client side, it could be hacked from the client side. There is a general agreement that whatever ‘resource’ is required to implement authentication between the client and the server is considered out-of-scope for REST. These authentication resources do not have to follow REST principles (see here for more details). REST Over HTTP When implementing REST over HTTP, the logical REST client is typically a web browser and the logical REST server is a web server. The REST API (or service) must be hypertext driven. About resource IDs:The preference is given to nouns rather than verbs to indicate the type of a resource (cat, dog, car…). The unique ID of a resource is a URI, for example: http://www.mysite.com/invoice/34657. A group of resources can also be accessed with a URI, for example: http://www.mysite.com/user/7723/invoices.It is also considered good practice to use URIs in resource representations when a resource refers to another resource. For example, in a XML document representing a resource: <dog self='www.mysite.com/dog/923' > <name>Lassie</name> <owner ref='www.mysite.com/owner/411' /> </dog> In order to perform operations on resources, simple HTTP is used to make calls between machines. HTTP knows several types of calls: PUT, GET, POST, DELETE, HEAD, CONNECT, PATCH, TRACE and OPTIONS. However, REST only uses four: PUT, GET, POST and DELETE.GET – Clients can request the status of a resource by making an HTTP GET request to the server, using the resource’s URI. REST requires that this operation does not produce any side effect to the resource’s status (nullipotent). PUT – Creates a new resource. Since the client does not know the next invoice number, the URI can be: http://www.mysite.com/invoice. If the resource is already created, it is not recreated. In other words, a REST PUT on http://www.mysite.com/invoice/841 (for example) is (and must be) idempotent. Invoice 841 must not be created multiple times if clients call that PUT several times. POST – REST requires POST client requests to update the corresponding resource with information provided by the client, or to create this resource if it does not exist. This operation is not idempotent. DELETE- This operation removes the resource forever. It is idempotent.REM: Implementing a http://www.mysite.com/invoice/add URI is not considered a REST compliant pratice. The format (JSON, XML…) used to return representations of resources is set in the media type of the server response (Multipurpose Internet Mail Extensions – MIME). In order to handle success or errors issues, HTTP REST recommends using one of the HTTP Status Code. Additional Readhttp://www.infoq.com/articles/rest-introductionReference: Introduction To REST Concepts from our JCG partner Jerome Versrynge at the Technical Notes blog. ...
java-logo

Java: The Checker Framework

One of the interesting tools I learned about at JavaOne 2012 is The Checker Framework. One of the Checker Framework’s web pages states that the Checker Framework ‘enhances Java’s type system to make it more powerful and useful,’ allowing software developers ‘to detect and prevent errors in their Java programs.’ One way to look at the Checker Framework is as an implementation of what JSR 305 (‘Annotations for Software Defect Detection’) might have been had it not fallen into the Dormant stage. The intention of JSR 308 (‘Annotations on Java Types’) is to ‘extend the Java annotation syntax to permit annotations on any occurrence of a type.’ Once JSR 308 is approved and becomes part of the Java programming language, annotations will be allowed in places they are not currently allowed. Although JSR 308 is still in Early Draft Review 2 stage, Checker Framework allows a developer to include commented-out annotation code in places not currently allowed until made available by JSR 308. It is important to note here that JSR 308 only makes annotations more generally available (specifies more types of source code against which they can be applied) and does not specify any new annotations. The Checker Framework requires Java SE 6 or later. The Checker Framework can be downloaded as a single ZIP file at http://types.cs.washington.edu/checker-framework/current/checkers.zip. The downloaded file can be unzipped to the directory checker-framework and then an environmental variable called CHECKERS can be set to point to that expanded directory’s subdirectory ‘checkers.’ For example, if the checkers.zip is unzipped to C:\checker-framework, then the environmental variable CHECKERS should be set to C:\checker-framework\checkers. One the Checker Framework checkers.zip has been downloaded, expanded, and pointed to by the CHECKERS environmental variable, it is time to try the Checker Framework out. The ‘long way’ of running the Checker Framework is shown next and is used with the -version tag to verify that Checker Framework is applied: Windows java -Xbootclasspath/p:%CHECKERS%/binary/jsr308-all.jar -jar %CHECKERS%/binary/jsr308-all.jar -version Linux java -Xbootclasspath/p:$CHECKERS/binary/jsr308-all.jar -jar $CHECKERS/binary/jsr308-all.jar -version The above should lead to output that looks something like that shown in the next screen snapshot.The installed Checker Framework can now be applied to compiling code. The next code listing shows a simple class that specifies that a method argument should not be null via the checkers.nullness.quals.NonNull (@NonNull) annotation. Example of Using Checker Framework’s @NonNull package dustin.examples;import checkers.nullness.quals.NonNull; import static java.lang.System.out;public class CheckersDemo { public void printNonNullToString(@NonNull final Object object) { out.println(object.toString()); }public static void main(final String[] arguments) { final CheckersDemo me = new CheckersDemo(); final String nullStr = null; me.printNonNullToString(nullStr); } } The above code listing shows a null being passed to a method with the argument annotated with @NonNull. NetBeans 7.3 flags this with the yellow squiggles and warning if hovered over. This is shown in the next screen snapshots.Although NetBeans flags the null setting of a parameter marked with the @NonNull annotation, the compiler builds that code without complaint. This is where the Checker Framework comes in. Because it’s a pain to type in the long command I showed previously, I either run the command shown above with a script or set up an alias as described in the Checker Framework Installation Instructions. In this case, I’ll use an alias like this: Setting Windows Command Line Alias for Java Checker doskey javachecker=java -Xbootclasspath/p:%CHECKERS%\binary\jsr308-all.jar -jar %CHECKERS%\binary\jsr308-all.jar $* The setting of this alias and running it with the -version flag is demonstrated in the next screen snapshot.It is far easier to apply this approach with the alias set. This can be used to compile the class in question as shown next (command using my ‘javachecker’ alias and image showing result). javachecker -d classes src\dustin\examples\*.javaThe above command demonstrates that I am able to use normal javac options such as -d to specify the destination directory for compiled .class files and pass along the Java source files to be compiled as normal. The example also demonstrates that without specifying the checker processor to run as part of the compilation, the @NotNull additional typing is not enforced during compilation. Before showing how to specify a processor to force the @NonNull to be be enforced during compilation, I want to quickly demonstrate that this compilation approach will still report standard compiler errors. Just for this example, I have renamed the ‘nullStr’ variable passed to the method of interest on line 17 to ‘nullStry’ so that it is a compiler error. The next two screen snapshots show this change (and NetBeans’s reported compilation error) and how the Checker Framework compilation approach also reports the javac error.Having shown that this approach to compilation compiles compilable code normally, reports compiler errors normally, and shows version appropriately, it is time to apply it to stronger type enforcement. I fix the compiler error in my code by removing the extra ‘y’ that I had added. Then, I need to pass -processor checkers.nullness.NullnessChecker as an additional flag and argument to the compilation process. Note that there are other processors besides NullnessChecker, but I am using NullnessChecker here to enforce the @NonNull at compile time. The following shows the command along with the output window demonstrating that command in action. Note that the compilation process is not allowed to complete and an error based on violation of the @NonNull typing is reported. javachecker -processor checkers.nullness.NullnessChecker -d classes src\dustin\examples\*.javaThis blog post has introduced the Checker Framework and shown how to quickly apply it to stronger type enforcement in Java source code. I only focused on one type of stronger typing here, but the Checker Framework supplies other built-in type checks and supports the option of writing custom type enforcement checks.   Reference: The Checker Framework from our JCG partner Dustin Marx at the Inspired by Actual Events 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:
Close