03 July 2014

Running GlassFish v3.1.2.2 on JDK 8

GlassFish v3 will simply not run on JDK 8 in the standard configuration but I found a little tweak to accomplish this.

Open the file
${GLASSFISH_HOME}/glassfish/config/osgi.properties
and add this line at the end:
jre-1.8=${jre-1.7}


Happy Coding!

24 April 2014

JDBC: Connection could not be allocated because:

Connection could not be allocated because: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. Please check the server.log for more details.

I stumbled about this Exception and wanted to let you know how I solved it for me. In my case that Exception comes from a GlassFish v4 instance interacting with a MySQL v5.5.37 database over JDBC v5.1.26. GlassFish wants to tell us that he can't receive any packages from the database but doesn't tell us exactly what's the reason. I figured out that the default value for the JDBC idle timeout are 300 secs but for MySQL the default value are (in my case) 180 secs. In this scenario MySQL is the server and GlassFish the client. The client connects to the server and keeps a connection. After 180 secs the server may kills the connection due to inactivity. The client does not get any information about this and keeps the connection for further 120 secs. If you call for data within these 120 secs you probably run into that exception because the connection is already closed and the client (GlassFish) complains with that exception.

So the solution is to lower the idle timeout in GlassFish to a value lower than 180 secs or raise the wait_timeout value in MySQL to a value bigger than 300 secs.

To change the idle timeout in GlassFish:
- Go to http://{ip of server or localhost}:4848/
- Go to Resources -> JDBC -> JDBC Connection Pools and select your pool
- Scroll down to Pool Settings and change the value of Idle Timeout:
- Hit Save

To change the wait_timeout in MySQL:
- Change the dir to /etc/mysql/
- Open the my.cnf file and search for a entry called wait_timeout
- Change the value and save the document (May you have to restart MySQL too).

Hope this helps and...


Happy Coding!

Introducing TabSwitch - A NetBeans IDE Plugin for efficiently switching Editor Tabs


I'm proud to announce my first NetBeans IDE Plugin called TabSwitch!
TabSwitch is a Plugin for efficiently switching Editor Tabs in NetBeans IDE.I'm using multiple tabs heavily in my Browser and I'am used to switch them with shortcuts like

⌥ + ⌘ + ←
and
⌥ + ⌘ + ➝
on Mac OS X or

Alt + Ctrl + ←
and
Alt + Ctrl + ➝
on Windows.

So I visited NetBeans Platform Training in Leipzig with Geertjan Wielanga, Anton Eppleton and Benno Markiewicz and wrote TabSwitch to use this feature in NetBeans IDE too.To be honest, NetBeans IDE already provides a similar feature which you can use with


⌘ + PAGE_UP
and
⌘ + PAGE_DOWN
on Mac OS X or

Ctrl + PAGE_UP
and
Ctrl + PAGE_DOWN
on Windows.

But if you work with that built-in feature for a while, you will notice, that it will switch between project tabs unexpectedly if you use the "tab-row-per-project" feature of NetBeans IDE. Which made this feature unuseable for me. With TabSwitch that's not the case! TabSwitch will preserve the project scope of the tabs. So if you reach the last tab of one project it will switch to the first tab of the next project and vice versa. Also TabSwitch will stay within the project tabs if you switch the tabs in a project tab group. Here's a picture which illustrates the behavior of TabSwitch:

Behavior of TabSwitch

You can download TabSwitch
from NetBeans Plugin Center here or
from the repository here.


I hope you like it and...


Happy Coding!

Filter Properties and pass them into Java Apps with Maven

If you create an app that will connect to other secured services, the day will come you have to add some developer keys or passwords. Or you want to simply define different environments (production, development, test) for your app running into e.g. for testing purposes. Changing that properties every time or pushing that properties to the repository would be a flaw.

Seriously, you should never push passwords etc. to your repository, no matter if it's private or not!

So what to do to prevent this? Passing that properties with Maven is one solution. Let's start!
Create a Maven Web Application Project if you haven't and open your pom.xml You will probably see a properties section, if not create one and add these properties:

./pom.xml

    ...
    Development
    default2

Now go to the build section and add

./pom.xml

    ...
    
        
            src/main/resources
            true
        
    
    ...

also add the following plugin to the build -> plugins section

./pom.xml

    ...
    
        ...
        
            org.apache.maven.plugins
            maven-resources-plugin
            2.6
            
                UTF-8
            
        
        ...
        
            org.apache.maven.plugins
            maven-war-plugin
            2.3
            
                false
                 
                     
                        ${basedir}/src/main/webapp/WEB-INF 
                         
                            web.xml 
                         
                        WEB-INF 
                        true 
                     
                 
            
        
        ...
    

Now the whole maven-part is done but we need some files to test our configuration.
Create a web.xml file under src/main/webapp/WEB-INF/ and fill in the following:

src/main/webapp/WEB-INF/web.xml
...
    
        javax.faces.PROJECT_STAGE${jsf.projectstage}
    
    
        Faces Servlet
        javax.faces.webapp.FacesServlet
        1
    
    
        Faces Servlet
        *.xhtml
    
    
        index.xhtml
    
    ...

Also add a index.xhtml file within src/main/webapp/ with the following code:

src/main/webapp/index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>#{facesContext.application.projectStage}</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <div>
            Project Stage: #{facesContext.application.projectStage}
        </div>
    </body>
</html>

Now you can Clean & Build the application and deploy it on your Application Server. The starting page index.xhtml will show you your actual project stage. The app will get the property <jsf.projectstage>Development</jsf.projectstage> from Maven and pass it into the web.xml. The web.xml is a Web Resource so the maven-war-plugin is responsible for that. Thus you can quickly change the JSF-Environment of your JSF-Application in the properties section of the Maven pom.xml. In addition you can pass that property when you trigger the build. For this simply execute the following line on the Terminal in your project dir:

mvn clean install -Djsf.projectstage=Production

Now we know the maven-war-plugin filters the web.xml but whats with that other stuff (maven-resources-plugin etc.)? With that you can filter not just Web Resource, you can filter usual resources. So let's do it. Create a filtered_resource.properties file under src/main/resources/

src/main/resources/filtered_resource.properties
filtered_value = ${property.2}

Now we need something to read the property. For that we create a Stateless EJB:

src/main/java/de/beanbelt/bbpassingpropertieswithmaven/OurService.java
@Stateless
public class OurService {

 public void readProperties() throws IOException {
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  InputStream stream = classLoader.getResourceAsStream("filtered_resource.properties");

  Properties properties = new Properties();
  properties.load(stream);

  String value = properties.getProperty("filtered_value", "not_filtered");

  System.out.println("Value: " + value);
 }
}

When you call the readProperties() method it will print the following on the console if everything is okay:

Reading properties...
Value: default2
...if not it will print:
Reading properties...
Value: not_filtered

That's it! Now you can pass properties into your Java Apps with Maven.

Happy Coding!

22 April 2014

Working with Java EE Interceptors and Repeatable Annotations

Since Java EE 6 you can invoke Interceptors around method calls. With Interceptors you will add Aspect-oriented Programming (AoP) patterns to your Java EE project. Given you have a method bound to an Interceptor a method call will look like this:

Overview and Behavior of Interceptors

To actually implement this behavior there are some simple steps to do. First implement an Interceptor:

@javax.interceptor.Interceptor
public class OurInterceptor {
    @javax.interceptor.AroundInvoke
    public Object someMethodName(InvocationContext context) throws Exception {

        // do something before method
        System.out.println(">before");

        //executing source method
        Object result = context.proceed();

        // do something after method
        System.out.println("<after");

        return result;
    }
}

And register our Interceptor in the beans.xml:



    
        de.beanbelt.bbinterceptorsandreapeatableannotations.interceptors.OurInterceptor
    

Now you can simply invoke this Interceptor by annotating a class or method in e.g. an Stateless EJB.

@Stateless
// interceptor will be invoked on every method in OurService
@javax.interceptor.Interceptors(OurInterceptor.class)
public class OurService {

    // You can invoke an Interceptor on one method only
    // Note: this will overwrite the class-level Interceptor
    //@Interceptors(OurInterceptor.class)
    public String getName(long id) {
        System.out.println("method");
        return database.get(id).getName();
    }
}

If you execute the code the following will be printed to the console:

>before
method
<after

Now we extends the example by our own annotations which will invoke the interceptor. Create an annotation that looks like the following:

@Inherited
@InterceptorBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OurAnnotation {
    @Nonbinding
    boolean someValue() default false;
}

And change the Interceptor like this:

@OurAnnotation
@javax.interceptor.Interceptor
public class OurInterceptor{...}

Now we can use the interceptor on method-level in OurService like this:

@Stateless
public class OurService {

    @OurAnnotation(someValue=true)
    public String getName(long id) {
        System.out.println("method");
        return database.get(id).getName();
    }
}

As you can see, we can pass parameters to the Annotation which we can read in our interceptor like this:

@OurAnnotation
@javax.interceptor.Interceptor
public class OurInterceptor{
    @javax.interceptor.AroundInvoke
    public Object someMethodName(InvocationContext context) throws Exception {
        Method method = context.getMethod();
        if (method.isAnnotationPresent(OurAnnotation.class)) {
            boolean someValue = method.getAnnotation(OurAnnotation.class).someValue();
            System.out.println("someValue is: "+someValue);
        }
        // do something before method
        System.out.println(">before");

        //executing source method
        Object result = context.proceed();

        // do something after method
        System.out.println("<after");

        return result;
    }

Since we annotated our method with someValue=true the output on the console will look like this:

someValue is: true
>before
method
<after

So far so good but what happens if we want to annotate our method multiple times like this?

@OurAnnotation(someValue=false)
    @OurAnnotation(someValue=true)
    public String getName(long id) {...}

We have to create a grouping Annotation (Note the S in OurAnnotationS).

@Inherited
@InterceptorBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OurAnnotations {
    @Nonbinding
    OurAnnotation[] value();
}

Now we can annotate our method like this:

@OurAnnotations({
        @OurAnnotation(someValue=false),
        @OurAnnotation(someValue=true)
    })    public String getName(long id) {...}

In Java 8 we can use the Repeatable Annotations feature. To do so we just need to add an Annotation to @OurAnnotation

@Inherited
@Repeatable(OurAnnotations.class)
@InterceptorBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OurAnnotation {...}

Now we can annotate our method as we stated before:

@OurAnnotation(someValue=false)
    @OurAnnotation(someValue=true)
    public String getName(long id) {...}

But what happened to the Interceptor, why is it not working anymore? Well, we have to implement a new interceptor for our grouping Annotation like this:

@OurAnnotations
@javax.interceptor.Interceptor
public class OurGroupingInterceptor{
    @javax.interceptor.AroundInvoke
    public Object someMethodName(InvocationContext context) throws Exception {
        Method method = context.getMethod();
        if (method.isAnnotationPresent(OurAnnotations.class)) {
               OurAnnotation[] ourAnnotations = method.getAnnotation(OurAnnotations.class).value();
            for (OurAnnotation annotation : ourAnnotations) {
                System.out.println("someValue is: "+ annotation.someValue());
            }
        }
        // do something before method
        System.out.println(">before");

        //executing source method
        Object result = context.proceed();

        // do something after method
        System.out.println("<after");

        return result;
    }
}

Now the output on the console will look like this:

someValue is: false
someValue is: true
>before
method
<after

Now we successfully implemented an Interceptor with our own Annotation which we can repeat like we want.


Happy Coding!