Thursday, October 28, 2010

Basic Authentication and Authorization

When building commercial applications the twin issues of authentication and authorization are almost certain to arise at some point, the topic becomes even livelier when you throw a legacy infrastructure into the mix and want everything to work seamlessly.

So what’s a really nice and simple way of doing this? Let’s look at Apache Shiro and see how it simplifies things for us.

What is Apache Shiro? I think they say it best themselves
Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application

Right - so let’s get our hands dirty, and see how we can leverage Shiro.


Create a Web application


New Project -> Maven -> Maven Web Application


Create a new Stateless Session Bean


HelloResource class

@Stateless
@Path("/message")
public class HelloResource {
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
        return "hello someone";
    }

} 

Note that under your PersonalHello web project Netbeans has created a RESTful web services node, under which your HelloResource lives.

Right click the RESTful Web Services node and Select REST Resources configuration.


Change the name of the REST Resources Path, this will make NetBeans generate the web.xml file with your servlet adaptor.

Run your web app and you should see the Standard ‘Hello World!’ index page.

Go to http://localhost:8080/PersonalHello/rest/message and you should see your ‘hello someone’ message.


So now we know that our simple web service with no authentication is working, lets add Shiro into the mix and see how complicated things become!


Adding Shiro 

Add  the following dependencies to your projects pom.xml

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.0.0-incubating</version>
        </dependency>
        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.6.1</version>
            <scope>runtime</scope>
        </dependency>

Note: Shiro has just graduated from the Apache Incubator, so expect a non-incubating release sometime soon.


Go to your web.xml and add the following



     <filter>
        <filter-name>ShiroFilter</filter-name>
        <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>

                # The IniShiroFilter configuration is very powerful and flexible, while still remaining succinct.
                # Please read the org.apache.shiro.web.servlet.IniShiroFilter JavaDoc for information.

                # Quick Tip: Instead of having this configuration here in web.xml, you can instead
                # move all of this to a 'shiro.ini' file at the root of the classpath and remove
                # the 'config' init-param. Or you can specify the 'configPath' init-param and specify the
                # path to a resource at any location (url, file or classpath). This may be desired if the
                # config gets long and you want to keep web.xml clean.

                [users]
                # format: username = password, role1, role2, ..., roleN
                root = secret,admin
                guest = guest,guest
                presidentskroob = 12345,president,admin
                darkhelmet = ludicrousspeed,darklord,schwartz
                lonestarr = vespa,goodguy,schwartz

                [roles]
                # format; roleName = permission1, permission2, ..., permissionN
                admin = *
                schwartz = lightsaber:*
                goodguy = winnebago:drive:eagle5

                [urls]
                /rest/** = authcBasic

            </param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>ShiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


Go New File -> Other -> properties



And add the following text to the file

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# This file is used to format all logging output
log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%c]: %m%n

# =============================================================================
# 3rd Party Libraries
# OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL
# =============================================================================
# ehcache caching manager:
log4j.logger.net.sf.ehcache=WARN

# Most all Apache libs:
log4j.logger.org.apache=WARN

# Quartz Enterprise Scheular (java 'cron' utility)
log4j.logger.org.quartz=WARN

# =============================================================================
# Apache Shiro
# =============================================================================
# Shiro security framework
log4j.logger.org.apache.shiro=TRACE
#log4j.logger.org.apache.shiro.realm.text.PropertiesRealm=INFO
#log4j.logger.org.apache.shiro.cache.ehcache.EhCache=INFO
#log4j.logger.org.apache.shiro.io=INFO
#log4j.logger.org.apache.shiro.web.servlet=INFO
log4j.logger.org.apache.shiro.util.ThreadContext=INFO








And finally let’s make our hello a little more personal. Change the sayHello method to the following


    public String sayHello() {

        StringBuilder builder = new StringBuilder();
        builder.append("Hello ");
        builder.append(SecurityUtils.getSubject().getPrincipal().toString());

        return builder.toString();
    }


Run your web-app again and go to http://localhost:8080/PersonalHello/rest/message you will now see a login prompt. Use ‘lonestarr’ as the user and ‘vespa’ as the password (or any of the other combinations that are in the config that you placed in the web.xml)
You will now be greeted by a personalised Hello, pretty nifty me think!

What have we done to achieve this?
1.    Added the dependencies to our project
2.    Made sure that log4j was configured
3.    Modified our web.xml with the Shiro specific config

  •     The important things to note here are:
         1. The Filter that in our case says every request must go through Shiro
         2. /rest/** = authcBasic  - This says that the urls here require basic authentication
         3. The users section

So not much work to achieve the authentication at all then.


Adding Authorization


Create a new class in your Web App:

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import org.apache.shiro.SecurityUtils;


public class AuthorizationInterceptor {

    @AroundInvoke
    public Object authenticate(InvocationContext context) throws Exception{

        if (!SecurityUtils.getSubject().hasRole("admin")){
            StringBuilder exBuilder = new StringBuilder();
            exBuilder.append("User: \'");
            exBuilder.append(SecurityUtils.getSubject().getPrincipal().toString());
            exBuilder.append("\' is not authorized to use this resource");


            throw new SecurityException(exBuilder.toString());
        }

        return context.proceed();
    }
}

And add the @Interceptors({AuthorizationInterceptor.class})  Annotation to your HelloResource class

package sparg.tim.personalhello;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.shiro.SecurityUtils;

/**
 *
 * @author tsparg
 */
@Interceptors({AuthorizationInterceptor.class})
@Stateless
@Path("/message")
public class HelloResource {
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {

        StringBuilder builder = new StringBuilder();
        builder.append("Hello ");
        builder.append(SecurityUtils.getSubject().getPrincipal().toString());


        return builder.toString();
    }

}

Run your application and go to http://localhost:8080/PersonalHello/rest/message and login with ‘guest’ username ‘guest’ password (or any user that is not a part of the admin group).

You should now see an error page telling you that you are not authenticated to view this page.

If you log in with any of the other user codes that are members of the admin role (look in your web.xml to see which) you will proceed to the normal screen.


A couple of things to note:
  • Shiro has some very nifty hooks into both Authentication and Authorization so that you can leverage any existing infrastructure that you may have.
  • With the Way I have done the Authorization the App Server returns a HTTP 500(Internal Error), it would be nice if I could figure out how to return a HTTP 401 (Unauthorized)
  • You should most probably make the AuthorizationInterceptor a Default Interceptor, meaning you wouldn't have to annotate your classes for authorization.


I quite like this approach, as the authorization and authentication can be quite clearly moved away from any domain specific code. 

Tuesday, October 26, 2010

Apologies to the Netbeans build system!

I need to make an apology - to the netbeans maven build system!

You see I spent so much time trying to get Glassfish work as an EJB backend, that when it swapped over to JBoss and things wheren't going my way from the outset I blamed the netbeans maven build system...

In my previous post I have an exceedingly long pom file removing all of the transitive dependencies from the JBoss-Client artifact.
If I had just had a little faith and not worked on an assumption, I would have discovered that the build system actually takes care of transitive dependencies for you!

What does this mean?
1) You don't actually need that whole (1000 line) pom file.

2) You can declare the dependancy as

        <dependency>
            <groupId>org.jboss.jbossas</groupId>
            <artifactId>jboss-as-client</artifactId>
            <version>5.1.0.GA</version>
            <type>pom</type>
        </dependency> 

instead of

        <dependency>
            <groupId>sparg.tim</groupId>
            <artifactId>JBossClientLibraries</artifactId>
            <version>5.10</version>
        </dependency>  

When you are creating the Netbeans platform application.

lesson - don't  make assumptions!

Friday, October 22, 2010

EJB backend and NetBeans Platform frontend


Sounds fairly straightforward right?
I also thought so initially. Unfortunately there are a couple nasty and not so little bumps that turn this from a trip to shops to neigh on the Roof of Africa Rally!

First step is easy, let’s use the bundled GlassFish App Server..

And there goes a frustrating couple of hours / days / weeks of your life, Let me explain.
GlassFish has a client jar ($GLASSFISH_HOME/modules/gf-client.jar) that you are supposed to include with your application to connect to the EJB backend. This all works fine when you are testing with your public static void main tests, however there are a couple of things to note that you will not be immediately apparent on your development machine.
  • gf-client.jar is just a meta-jar, all that it does is reference other jars, which in turn can reference other jars ad infinitum.
  • The moment you take your test application off your computer it will fail. In all likelihood you have included gf-client.jar, but you haven’t included all of its references. What this means is that you have got to install GlassFish App Server on all of the computers that you want to install your software on, or figure out what the dependency tree is (I’ll save you some time, it’s pretty much the same as installing, You get about every single jar that is included in the full install)
  • After you’ve figured all of this out, your Netbeans application still will not run. Why? Read here and here to understand the problem.


Right let’s get this show back on the road. What are we going to need in order to get this to work?
  1. NetBeans
  2. Maven
  3. JBoss
  4. Patience

 

Setting up the JBoss Client Libraries


First off what you need to do is find all of the JBoss Client Dependencies and create a Maven artifact from them. Thankfully I didn’t need to do that, somebody had already figured it out for me.
Here’s the pom file


        4.0.0
        sparg.tim
        JBossClientLibraries
        jar
        5.10
        JBossClientLibraries
        http://maven.apache.org
        
            
                org.jboss.javaee
                jboss-javaee
                5.0.1.GA
            
            
                org.hibernate
                hibernate-annotations
                3.4.0.GA
                
                    
                        org.hibernate
                        hibernate-commons-annotations
                    
                    
                        org.hibernate
                        hibernate-core
                    
                    
                        dom4j
                        dom4j
                    
                
            
            
                org.jboss.naming
                jnp-client
                5.0.3.GA
            
            
                oswego-concurrent
                concurrent
                1.3.4-jboss-update1
            
            
                org.jboss.ejb3
                jboss-ejb3-proxy-clustered
                1.0.1
                client
                
                    
                        org.jboss.ejb3
                        jboss-ejb3-proxy-impl
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-proxy-spi
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-api
                    
                
            
            
                org.jboss.ejb3
                jboss-ejb3-proxy-spi
                1.0.0
                client
            
            
                org.jboss.ejb3
                jboss-ejb3-proxy-impl
                1.0.2
                client
                
                    
                        org.jboss.aspects
                        jboss-remoting-aspects
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-common
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-proxy-spi
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-interceptors
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                    
                        org.jboss.naming
                        jnpserver
                    
                
            
            
                org.jboss.ejb3
                jboss-ejb3-core
                1.1.5
                client
                
                    
                        javassist
                        javassist
                    
                    
                        org.hibernate
                        hibernate
                    
                    
                        org.hibernate
                        hibernate-entitymanager
                    
                    
                        org.jboss.integration
                        jboss-jca-spi
                    
                    
                        org.jboss
                        jboss-vfs
                    
                    
                        org.jboss.aop
                        jboss-aop
                    
                    
                        org.jboss.aop
                        jboss-aop-aspects
                    
                    
                        org.jboss.cache
                        jbosscache-core
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-cache
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-endpoint
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-security
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-timerservice-spi
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-ext-api-impl
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-metadata
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-proxy-clustered
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-transactions
                    
                    
                        org.jboss.javaee
                        jboss-ejb-api
                    
                    
                        org.jboss.javaee
                        jboss-jacc-api
                    
                    
                        org.jboss.javaee
                        jboss-jca-api
                    
                    
                        org.jboss.javaee
                        jboss-jms-api
                    
                    
                        org.jboss.jpa
                        jboss-jpa-deployers
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                    
                        org.jboss.microcontainer
                        jboss-kernel
                    
                    
                        org.jboss.security
                        jbosssx
                    
                    
                        org.jboss.ws
                        jbossws-spi
                    
                    
                        quartz
                        quartz
                    
                    
                        sun-jaxws
                        jaxws-api
                    
                    
                        sun-jaxws
                        jsr181-api
                    
                    
                        org.jboss.aspects
                        jboss-remoting-aspects
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-api
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-common
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-interceptors
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-proxy-impl
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-proxy-spi
                    
                
            
            
                org.jboss.remoting
                jboss-remoting
                2.5.1
            
            
                org.jboss.deployers
                jboss-deployers-core-spi
                2.0.7.GA
            
            
                org.jboss.deployers
                jboss-deployers-core
                2.0.7.GA
            
            
                org.jboss.jbossas
                jboss-as-main
                5.1.0.GA
                client
                
                    
                        org.jboss.bootstrap
                        jboss-bootstrap
                    
                    
                        gnu-getopt
                        getopt
                    
                    
                        log4j
                        log4j
                    
                    
                        org.jboss.logbridge
                        jboss-logbridge
                    
                
            
            
                org.jboss.jbossas
                jboss-as-j2se
                5.1.0.GA
                
                    
                        org.jboss.integration
                        jboss-classloading-spi
                    
                    
                        apache-xerces
                        xml-apis
                    
                
            
            
                org.jboss.ejb3
                jboss-ejb3-ext-api
                1.0.0
                
                    
                        org.jboss.javaee
                        jboss-ejb-api
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                
            
            
                org.jboss.jbossas
                jboss-as-server
                5.1.0.GA
                client
                
                    
                        sun-jaxb
                        jaxb-api
                    
                    
                        org.jboss.jbossas
                        jboss-as-deployment
                    
                    
                        org.jboss.bootstrap
                        jboss-bootstrap
                    
                    
                        org.jboss.integration
                        jboss-deployment-spi
                    
                    
                        org.jboss.jpa
                        jboss-jpa-deployers
                    
                    
                        org.jboss.security
                        jbosssx
                    
                    
                        log4j
                        log4j
                    
                    
                        org.jboss.jbossas
                        jboss-as-system-jmx
                    
                    
                        org.jboss.jbossas
                        jboss-as-jmx
                    
                    
                        org.jboss.jbossas
                        jboss-as-system
                    
                    
                        org.jboss.integration
                        jboss-transaction-spi
                    
                    
                        org.jboss.javaee
                        jboss-jacc-api
                    
                    
                        org.jboss.javaee
                        jboss-jms-api
                    
                    
                        org.jboss.ws.native
                        jbossws-native-saaj
                    
                    
                        org.jboss.ws.native
                        jbossws-native-jaxws
                    
                    
                        javax.security
                        jaas
                    
                    
                        org.jboss.javaee
                        jboss-jca-api
                    
                    
                        bcel
                        bcel
                    
                    
                        jpl-util
                        jpl-util
                    
                    
                        jpl-pattern
                        jpl-pattern
                    
                    
                        org.jboss
                        jbossxb
                    
                    
                        org.jboss.naming
                        jnp-server
                    
                    
                        gnu-getopt
                        getopt
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                    
                        org.jboss.javaee
                        jboss-ejb-api
                    
                    
                        org.jboss.naming
                        jnpserver
                    
                
            
            
                org.jboss.ejb3
                jboss-ejb3-security
                1.0.0
                client
                
                    
                        org.jboss.aspects
                        jboss-current-invocation-aspects
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-interceptors
                    
                    
                        org.jboss.security
                        jbosssx
                    
                    
                        org.jboss.javaee
                        jboss-jacc-api
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-ext-api-impl
                    
                    
                        org.jboss.aop
                        jboss-aop
                    
                    
                        org.jboss.ejb3
                        jboss-ejb3-metadata
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                
            
            
                org.jboss.security
                jbosssx-client
                2.0.3.SP1
            
            
                org.jboss.deployers
                jboss-deployers-client
                2.0.7.GA
            
            
                org.jboss.deployers
                jboss-deployers-client-spi
                2.0.7.GA
                
                    
                        org.jboss.man
                        jboss-managed
                    
                
            
            
                org.jboss.jbossas
                jboss-as-system-jmx
                5.1.0.GA
                client
                
                    
                        apache-xerces
                        xml-apis
                    
                    
                        org.jboss
                        jboss-vfs
                    
                    
                        org.jboss
                        jbossxb
                    
                    
                        org.jboss.deployers
                        jboss-deployers-impl
                    
                    
                        org.jboss.deployers
                        jboss-deployers-structure-spi
                    
                    
                        org.jboss.deployers
                        jboss-deployers-vfs
                    
                    
                        org.jboss.deployers
                        jboss-deployers-vfs-spi
                    
                    
                        org.jboss.bootstrap
                        jboss-bootstrap
                    
                    
                        org.jboss.jbossas
                        jboss-as-system
                    
                    
                        org.jboss.jbossas
                        jboss-as-jmx
                    
                    
                        org.jboss.microcontainer
                        jboss-dependency
                    
                    
                        org.jboss.microcontainer
                        jboss-kernel
                    
                
            
            
                org.jboss.slf4j
                slf4j-jboss-logging
                1.0.2.GA
            
            
                org.jboss.logging
                jboss-logging-jdk
                2.1.0.GA
            
            
                org.jboss.logging
                jboss-logging-log4j
                2.1.0.GA
                
                    
                        log4j
                        log4j
                    
                
            
            
                org.jboss.logging
                jboss-logging-spi
                2.1.0.GA
            
            
                org.jboss.ejb3
                jboss-ejb3-common
                1.0.0
                client
                
                    
                        org.jboss.microcontainer
                        jboss-kernel
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                    
                        org.jboss.deployers
                        jboss-deployers-spi
                    
                
            
            
                org.jboss.jbossas
                jboss-as-server
                5.1.0.GA
                jmx-invoker-adaptor-client
                
                    
                        sun-jaxb
                        jabx-api
                    
                    
                        org.jboss.jbossas
                        jboss-as-deployment
                    
                    
                        org.jboss.bootstrap
                        jboss-bootstrap
                    
                    
                        org.jboss.integration
                        jboss-deployment-spi
                    
                    
                        org.jboss.jpa
                        jbopss-jpa-deployers
                    
                    
                        org.jboss.security
                        jbosssx
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                    
                        log4j
                        log4j
                    
                    
                        org.jboss.jbossas
                        jboss-as-system-jmx
                    
                    
                        org.jboss.jbossas
                        jboss-as-jmx
                    
                    
                        org.jboss.jbossas
                        jboss-as-system
                    
                    
                        org.jboss.javaee
                        jboss-ejb-api
                    
                    
                        org.jboss.jbossas
                        jboss-as-security
                    
                    
                        org.jboss.integration
                        jboss-transaction-spi
                    
                    
                        org.jboss.javaee
                        jboss-jacc-api
                    
                    
                        org.jboss.jbossas
                        jboss-jms-api
                    
                    
                        org.jboss.ws.native
                        jbossws-native-saaj
                    
                    
                        org.jboss.ws.native
                        jbossws-native-jaxws
                    
                    
                        javax.security
                        jaas
                    
                    
                        org.jboss.javaee
                        jboss-jca-api
                    
                    
                        bcel
                        bcel
                    
                    
                        jpl-util
                        jpl-util
                    
                    
                        jpl-pattern
                        jpl-pattern
                    
                    
                        org.jboss
                        jbossxb
                    
                    
                        org.jboss.naming
                        jnpserver
                    
                    
                        gnu-getopt
                        getopt
                    
                    
                        sun-jaxb
                        jaxb-api
                    
                    
                        org.jboss.jpa
                        jboss-jpa-deployers
                    
                    
                        org.jboss.javaee
                        jboss-jms-api
                    
                
            
            
                org.jboss.jbossas
                jboss-as-management
                5.1.0.GA
                jsr77-client
                
                    
                        org.jboss.deployers
                        jboss-deployers-vfs
                    
                    
                        org.jboss.microcontainer
                        jboss-kernel
                    
                    
                        org.jboss.cl
                        jboss-classloading-vfs
                    
                    
                        org.jboss.jbossas
                        jboss-as-server
                    
                    
                        org.jboss.jbossas
                        jboss-as-system
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-api
                    
                    
                        org.jboss.bootstrap
                        jboss-bootstrap
                    
                    
                        org.jboss.jbossas
                        jboss-as-connector
                    
                    
                        org.jboss.jbossas
                        jboss-as-cluster
                    
                    
                        apache-xerces
                        xml-apis
                    
                
            
            
                org.jboss.jbossas
                jboss-as-iiop
                5.1.0.GA
                client
                
                    
                        apache-avalon
                        avalon-framework
                    
                    
                        apache-xerces
                        xml-apis
                    
                    
                        jacorb
                        jacorb
                    
                    
                        javax.security
                        jaas
                    
                    
                        javax.transcation
                        jta
                    
                    
                        log4j
                        log4j
                    
                    
                        org.jboss.integration
                        jboss-classloading-spi
                    
                    
                        org.jboss.integration
                        jboss-corba-ots-spi
                    
                    
                        org.jboss.integration
                        jboss-transaction-spi
                    
                    
                        org.jboss.javaee
                        jboss-ejb-api
                    
                    
                        org.jboss.jbossas
                        jboss-as-main
                    
                    
                        org.jboss.jbossas
                        jboss-as-server
                    
                    
                        org.jboss.jbossas
                        jboss-as-security
                    
                    
                        org.jboss.jbossas
                        jboss-as-system
                    
                    
                        org.jboss.jbossas
                        jboss-as-system-jmx
                    
                    
                        org.jboss.metadata
                        jboss-metadata
                    
                    
                        javax.transaction
                        jta
                    
                
            
            
                org.jboss.cluster
                jboss-ha-client
                1.1.1.GA
                
                    
                        org.jboss.aspects
                        jboss-remoting-aspects
                    
                
            
            
                org.jboss.jbossas
                jboss-as-cluster
                5.1.0.GA
                jboss-ha-legacy-client
                
                    
                        log4j
                        log4j
                    
                    
                        org.jboss.jbossas
                        jboss-as-server
                    
                    
                        jgroups
                        jgroups
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-api
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-cache-spi
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-jbc
                    
                    
                        org.jboss.cluster
                        jboss-ha-server-cache-jbc
                    
                    
                        org.jboss.jbossas
                        jboss-as-system-jmx
                    
                    
                        org.jboss.jbossas
                        jboss-as-system
                    
                    
                        org.jboss.bootstrap
                        jboss-bootstrap
                    
                    
                        javax.transaction
                        jta
                    
                
            
            
                org.slf4j
                slf4j-api
                1.5.6
            
            
                org.jboss.aop
                jboss-aop
                2.1.1.GA
                client
                
                    
                        apache-xerces
                        xml-apis
                    
                    
                        org.apache.ant
                        ant
                    
                    
                        javassist
                        javassist
                    
                    
                        org.jboss
                        jboss-reflect
                    
                    
                        qdox
                        qdox
                    
                    
                        trove
                        trove
                    
                    
                        log4j
                        log4j
                    
                
            
            
                org.jboss
                jboss-common-core
                2.2.14.GA
            
            
                org.jboss.security
                jboss-security-spi
                2.0.3.SP1
            
            
                org.jboss
                jboss-mdr
                2.0.1.GA
                
                    
                        org.jboss
                        jboss-reflect
                    
                
            
            
                org.jboss.client
                jboss-client
                5.1.0.CR1
            
            
                org.apache
                xmlsec
                1.4.2
            
            
                commons-logging
                commons-logging
                1.1.0.jboss
            
            
                org.jboss.integration
                jboss-integration
                5.1.0.GA
            
            
                jboss.messaging
                jboss-messaging
                1.4.3.GA
            
            
                jboss
                jboss-serialization
                1.0.3.GA
            
            
                org.hibernate
                ejb3-persistence
                1.0.2.GA
            
            
                org.jboss.aspects
                jboss-remoting-aspects
                1.0.2
                
                    
                        org.jboss.aop
                        jboss-aop
                    
                    
                        org.jboss.microcontainer
                        jboss-kernel
                    
                    
                        org.jboss.security
                        jbosssx
                    
                
            
            
                javassist
                javassist
                3.10.0.GA
            
        
        
        
            
                
                    maven-assembly-plugin
                    
                        
                            jar-with-dependencies
                        
                        false
                        JBossClientLibraries-5.10-full
                    
                    
                        
                            make-my-jar-with-dependencies
                            package
                            
                                single
                            
                        
                    
                
            
        
    



Even here things are not straightforward. (If somebody knows of a better way of doing the following section please tell me).
We need to take the JBossClientLibraries-5.10-full.jar and edit it to remove everything out of the META-INF/maven folder except your artifact details. So in my example everything we be deleted except the sparg.tim folder and its contents.
We can now install this to a repository as an artifact.

Create the Maven EJB Project


After that initial setup things become much the way they should be – simple!



New Project -> Maven EJB Module


Don’t forget to set your Java EE Version to 5, as JBoss does not yet have support for EE 6.

Go File -> new -> Session Bean




Create a business method.


HelloBean class
package sparg.tim.simpleejb;

import javax.ejb.Stateless;

/**
 *
 * @author tsparg
 */
@Stateless
public class HelloBean implements HelloBeanRemote {

    public String getMessage() {
        return "Hello Netbeans";
    }
}


HelloBeanRemote Class

HelloBeanRemote 
package sparg.tim.simpleejb;

import javax.ejb.Remote;

/**
 *
 * @author tsparg
 */
@Remote
public interface HelloBeanRemote {

    String getMessage();
    
}


Right click on your project -> properties -> run and select the JBoss app server.
You can now run the EJB project.

Create NetBeans Platform application


File -> new Project -> Maven -> Maven NetBeans Application


Create the module project with the application (JBossClient-core in my example).
Navigate to your core module and add a dependency – this will be the artifact that we created right in the beginning.



Do the same procedure with the EJB Module you’ve just created, this time you should just be able to click the ‘Open Projects’ tab and  select it from there.



Create a new TopComponent, new -> Window.
Make it Open on application Start, in the Editor Position.



I called mine HelloTopComponent.

Drag a Button and label onto the screen



Double click the button to get its ActionHandler.

The pertinent code is

private void btnGetMessageActionPerformed(java.awt.event.ActionEvent evt) {
        Properties props = new Properties();
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        properties.put(Context.PROVIDER_URL, "127.0.0.1:1099");
        InitialContext ctx;
        try {
            ctx = new InitialContext(properties);
            HelloBeanRemote remote = (HelloBeanRemote) ctx.lookup("HelloBean/remote-sparg.tim.simplejb.HelloBeanRemote");
            lblOutput.setText(remote.getMessage());
            System.out.println(remote.getMessage());
        } catch (NamingException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

It is important to note that this line


HelloBeanRemote remote = 
(HelloBeanRemote) ctx.lookup(
"HelloBean/remote-sparg.tim.simplejb.HelloBeanRemote");




Will more than likely look different on your system

Now if you’ve managed to get this right, and exercised large amounts of patience – when you click the getMessage button you will get this oh so sweet screen




Although this has taken me a lot longer to figure out than I ever would have guessed, I'm pretty happy just to have the stuff up and running.
It would have been nice for GlassFish to have worked in the role that I have JBoss fulfilling currently - purely because of the tighter integration between GlassFish and the Netbeans communities.

EDIT: please see this post to make this process a whole load shorter

Friday, September 17, 2010

Are Application Client Containers ever used?

Has anybody actually ever used Application Client Containers?
The only examples I've ever seen have been have been trivial examples involving a single class that does everything.

We've been investigating using this for some new software but everytime i hit a problem I feel like I'm going down the rabbit hole.

Just setting the client up to work with the EJB backend is an absolute mission, requiring copy and erroring from various web sites and tutorials in order to get things working.
And then when you try and pull the client onto a seperate computer from yout application server everything falls apart again!

I'm starting to think that Application Client Containers have very little real world usage, and that everybody is communicating via web services or their own proprietary protocols.

But maybe I've gone down the rabbit hole and haven't emerged from the other side yet?

Friday, September 10, 2010

Archaic Crystal Reports 2008

So you're happily creating reports for your users, no mess no fuss.

All of a sudden it breaks. Not in the literal black smoke way but more in the espionage agent got into your software way. Your output is all over the place - some lines overwrite others, some just disappear, in short the output is garbled.

I spent ages pondering what could actually be the problem, I mean this stuff was working correctly at other client sights. Was it Windows 7, an update to Dot Net, well whatever the problem is the latest Crystal Reports service pack will fix it... yeah right.

The problem is this - Crystal Reports 2008 (And all versions prior to that)  rely on the printer driver to generate their output. That is truly archaic.
Now in the event that you don't think that is such a big deal (stop being an idiot and set the default printer to one that you know works... duh) there are some lurking issues.
Windows comes preinstalled with this thing called the 'Microsoft XPS Document Writer' which is by default your default printer.
Any guesses as to what happens when this is set to your default printer and you try and generate reports? The KGB agent sneaks into the generation process is what...

Right so then you remove the offending printer from that machine - all sorted, right?
Well no. You see if you remote desktop onto that computer that is generating the reports, your default printer becomes that machines default printer.
So if your default printer is the Microsoft XPS document Writer you will eventually spot the issue, however if like any other sane person out there you actually have a real printer then everything looks like its running perfectly and you curse the clients for their stupidity.

I say it again Crystal Reports is archaic!

Does anybody know of a way to convert crystal report files to any other reporting software?

Friday, August 27, 2010

Kickstarting GlassFish Embedded JMS

We've started migrating our messaging onto GlassFish and its embedded messaging, and in the process discovered an oddity.

If you only use GlassFish for its JMS facilities, and don't have an EJB or web application that uses the JMS then GlassFish doesn't start it.

I've been told that in the next release you will be able to set the 'org.glassfish.jms.EagerStartup=true' system property which will start the JMS up at GlassFish start up.

But until then this is how i've found to get round it.

  1. Create a JMS Pool in GlassFish
  2. Create a dummy application that initializes the the embedded JMS

Here are the settings that I used in GlassFish 


Here is the Code for the little dummy application that boots the embedded JMS into action.
package sparg.tim;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.jms.ConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


@Singleton
@Startup
public class KickStartBean {

    @PostConstruct
    public void initMessaging(){
        try {
            Context context = new InitialContext();
            ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("JMSInitPool");
            Logger.getLogger(KickStartBean.class.getName()).log(Level.INFO,
                    "CF Systems: JMS HAS INITIALIZED");
        } catch (NamingException ex) {
            Logger.getLogger(KickStartBean.class.getName()).log(Level.SEVERE, 
                    "CF Systems: JMS HAS FAILED TO INITIALIZED", ex);
        }

    } 
}


voila! You now have a GlassFish appServer that automatically start its JMS. Now I eagerly await the new version that will allow me to take out this little hack...

Installing GlassFish as a windows service

I would think installing GlassFish as a service is a fairly common requirement, however I battled to find any concise documentation on how to do this, so here's my bash.

I'm going to assume the following:
  • GlassFish is installed to c:\GlassFishv3
  • The GlassFish bin directory has been added to your path (c:\GlassFishv3\bin)
  • GlassFish 3.0.1
right now down to it, run the following statement:
asadmin create-service



















Easy enough, but I don't like the service name domain1 - as it is rather uninformative, I would much prefer a name like say GlassFish


cd glassfishv3\glassfish\domains\domain1\bin
notepad domain1Service.xml

This shows a file something like this



  domain1
  domain1 GlassFish Server
  GlassFish Server
  C:/glassfishv3/glassfish/bin/asadmin.bat
  C:/glassfishv3/glassfish/domains/domain1/bin
  reset
  tcpip
  start-domain
  --verbose
  --domaindir
  C:/glassfishv3/glassfish/domains
  domain1
  stop-domain
  --domaindir
  C:/glassfishv3/glassfish/domains
  domain1
The important elements for us are these


  domain1
  domain1 GlassFish Server
  GlassFish Server

Lets Change them to something more friendly like


  GlassFish 3.0.1
  GlassFish 3.0.1
  GlassFish 3.0.1 Server
Or whatever fits your needs.
Right now to round it off, run the thiese last 2 commands
Cd glassfish\3.0.1\glassfish\domains\domain1\bin
domain1Service.exe uninstall
domain1Service.exe install

You now have GlassFish installed with a service name of your choosing.