Install this theme

Posts tagged: java

Java: Input Stream generating random characters

Quick and dirty implementation of the Java’s InputStream, that can generate a desired number of random characters, without buffering it in memory. May be useful for unit testing.

import org.apache.commons.lang3.RandomStringUtils;
import java.io.IOException;
import java.io.InputStream;

public class RandomCharsInputStream extends InputStream {

    private static final int ALPHABETIC = 1;

    private static final int ALPHANUMERIC = 2;

    private static final int ASCII = 3;

    private static final int NUMERIC = 4;

    private static final int CHARS = 5;

    private int type = ALPHABETIC;

    private long size = 0;

    private long charsRead = 0;

    private char[] chars;

    public static final RandomCharsInputStream newAlphabetic(long size) {
        return new RandomCharsInputStream(size, ALPHABETIC);
    }

    public static final RandomCharsInputStream newAlphanumeric(long size) {
        return new RandomCharsInputStream(size, ALPHANUMERIC);
    }

    public static final RandomCharsInputStream newAscii(long size) {
        return new RandomCharsInputStream(size, ASCII);
    }

    public static final RandomCharsInputStream newNumeric(long size) {
        return new RandomCharsInputStream(size, NUMERIC);
    }

    public static final RandomCharsInputStream newWithChars(long size, char... chars) {
        return new RandomCharsInputStream(size, chars);
    }

    public static final RandomCharsInputStream newWithChars(long size, String chars) {
        return new RandomCharsInputStream(size, chars.toCharArray());
    }

    private RandomCharsInputStream(long size, int type) {
        this.size = size;
        this.type = type;
    }

    private RandomCharsInputStream(long size, char... chars) {
        this.size = size;
        this.type = CHARS;
        this.chars = chars;
    }

    @Override
    public int read() throws IOException {
        if (charsRead >= size)
            return -1;

        char c;
        switch (type) {
            case ALPHABETIC:
                c = RandomStringUtils.randomAlphabetic(1).charAt(0);
                break;

            case ALPHANUMERIC:
                c = RandomStringUtils.randomAlphanumeric(1).charAt(0);
                break;

            case ASCII:
                c = RandomStringUtils.randomAscii(1).charAt(0);
                break;

            case NUMERIC:
                c = RandomStringUtils.randomNumeric(1).charAt(0);
                break;

            case CHARS:
                c = RandomStringUtils.random(1, chars).charAt(0);
                break;

            default:
                throw new IllegalArgumentException("Unknown random type: " + type);
        }

        charsRead++;
        return c;
    }
}    

Usage examples:

RandomCharsInputStream in = RandomCharsInputStream.newAscii(10000);

RandomCharsInputStream in = RandomCharsInputStream.newNumeric(100);

RandomCharsInputStream in = RandomCharsInputStream.newWithChars(30, "xyz");
Load/Drop Jars to/from Oracle database using Ant

Oracle Client Package provides loadjava and dropjava tools to loading/dropping java classes / jars / resources to/from the Oracle database. 

Sometimes however it is necessary to run this functionality on the machine that doesn’t have Oracle Client package installed.

This post describes how to achieve this using Ant.

Note! This instruction is for Oracle 11g.

Prerequisites

From the machine having Oracle Client installed, copy ojdbc5.jar (typically located in $ORACLE_HOME/product/11.x/client_1/jdbc/lib) and aurora.zip (typically located in $ORACLE_HOME%/product/11.x/client_1/javavm/lib) to some folder accessible by your Ant script.

Below i’ll assume, that this 2 files are located in the same folder where the Ant script located.

Load Java Target

<target name="loadjava" description="target for deploying jars to the database">
	<java classname="oracle.aurora.server.tools.loadjava.LoadJavaMain" fork="true">
		<jvmarg value="-Xint" />
		<classpath>
			<pathelement location="aurora.zip" />
			<pathelement location="ojdbc5.jar" />
		</classpath>
		<arg line="-thin -user SCOTT/TIGER@DBHOST:1551:DBSID -resolve my-jar-to-upload.jar" />
	</java>
</target> 

This target will deploy my-jar-to-upload.jar file to the Oracle database identified by SCOTT/TIGER@DBHOST:1551:DBSID url.

Drop Java Target

<target name="dropjava" description="target for dropping jars from the database">
	<java classname="oracle.aurora.server.tools.loadjava.DropJavaMain" fork="true">
		<jvmarg value="-Xint" />
		<classpath>
			<pathelement location="aurora.zip" />
			<pathelement location="ojdbc5.jar" />
		</classpath>
		<arg line="-thin -user SCOTT/TIGER@DBHOST:1551:DBSID my-jar-to-upload.jar" />
	</java>
</target> 

This target will drop my-jar-to-upload.jar file from the Oracle database identified by SCOTT/TIGER@DBHOST:1551:DBSID url.

Database-driven unit tests with Liquibase

In the previous article “Database change management with Liquibase” i demonstrated the standard Liquibase usage for managing database changes.

This post will describe, how to construct an infstructure for executing database-driven unit tests, a more likely untypical task for Liquibase.

To be able to execute database-driven tests we have to put our database into a known state between test runs. This is where Liquibase will help us.

First, let’s create a sample set of changes that populates the database with the test data:

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
	<changeSet id="testdata" author="bar">
		<loadData tableName="t_role" file="db/testdata/roles.csv">
			<column name="name" type="STRING" />
			<column name="description" type="STRING" />
		</loadData>
		<loadData tableName="t_user" file="db/testdata/users.csv">
			<column name="id" type="NUMERIC" />
			<column name="username" type="STRING" />
			<column name="role" type="STRING" />
		</loadData>
		<loadData tableName="t_address" file="db/testdata/addresses.csv" />
		<rollback>
			<delete tableName="t_address" />
			<delete tableName="t_user" />
			<delete tableName="t_role" />
		</rollback>
	</changeSet>
</databaseChangeLog> 

In the changelog above we make use of the <loadData> tag that is able to load data from the CSV file and insert it into the database (alternatively you may use <insert>, <update> and <delete> tags to manipulate the database contents). Furthermore the <rollback> block describes how to remove the inserted changes from the database.

As brief overview, here is an example of the roles.csv file:

name,description
USER,A simple user
ADMIN,Administrator user
ANONYMOUS,NULL 

First row in the CSV file specifies the column names to populate. All subsequent rows contains the test data.

Please consult GitHub for other CSV files used in this post: https://github.com/bigpuritz/javaforge-blog/tree/master/liquibase-sample/db/testdata

Now, let’s make our project ready to use Liquibase together with the Junit.

Keep reading

Using XSDs or any other custom resources as Maven dependencies

Often it is required to put some custom resources (e.g. XSDs, WSDLs etc.) under dependency management control.

As soon as Maven is a de facto standard dependency management mechanism in the Java world, this post demonstrates how to use it to manage untypical custom resources as dependencies within the pom.xml.

Let’s assume we have some xsd file (test.xsd in this example), that we want to use as dependency in our POM.

First, we’ll deploy it to the local repository (alternatively you can deploy it to your company’s internal maven repository):

mvn install:install-file -Dfile=test.xsd -DgroupId=com.mycompany.app \
           -DartifactId=app-xsd -Dversion=1.0.0 -Dtype=xsd -Dpackaging=xsd

After installation you’ll find the xsd in your local maven repository within the following folder structure:

image

Next referencing this file as a dependency in your POM is quite simple. Just write:

<dependency>
	<groupId>com.mycompany.app</groupId>
	<artifactId>app-xsd</artifactId>
	<version>1.0.0</version>
	<type>xsd</type>
</dependency>	 

Furthermore if you want to add this file as a resource to the final artifact generated by Maven, you have to configure maven-dependency-plugin in your POM like this:

<build>
	<plugins>
		...
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-dependency-plugin</artifactId>
			<version>2.5.1</version>
			<executions>
				<execution>
					<id>copy-dependencies</id>
					<phase>generate-resources</phase>
					<goals>
						<goal>copy-dependencies</goal>
					</goals>
					<configuration>
						<outputDirectory>${project.build.directory}/${project.build.finalName}/META-INF</outputDirectory>
						<includeArtifactIds>app-xsd</includeArtifactIds>
						<includeTypes>xsd</includeTypes>
					</configuration>
				</execution>
			</executions>
		</plugin>
		...
	</plugins>		
</build> 

After executing the maven build the app-xsd-1.0.0.xsd file will land in the artifact’s META-INF folder.

Sending iOS push notifications using Apache Camel and Boxcar.io

Apache Camel is a rule-based routing and mediation engine providing implementation of Enterprise Integration Patterns. It allows message transfer from different sources to different destinations (see http://camel.apache.org/components.html for further details).

Playing around with Apache Camel i’ve decided to write a simple example sending push notifications to the iOS devices. 

One option is to use original Camel’s Apns Component. This requires however your APNS provider has to be registered by Apple in order to send push notifications using generated certificate.

Another option is to use a free, public available APNS provider. In this example I’ll use Boxcar.IO as an APNS provider.

Boxcar allows you to create your own provider (= boxcar account) and send push notifications through it to the free Boxcar App installed on your iOS device. Alternatively (for testing or development purpose) one of the pre-configured, generic providers can be used (i’ll use generic “Monitoring” provider in this post).

Furthermore Boxcar exposes a very simple REST API containing only 3 RESTful requests: SUBSCRIBE, CREATE and BROADCAST. SUBSCRIBE will add your service for a user. CREATE sends a message to one user, or a subset of your users. BROADCAST sends a single message to all of your users.

Let’s prepare the iOS device for using Boxcar first.

Keep reading

Atmosphere per Session Broadcaster

Atmosphere is a WebSocket/Comet Framework for Java (and other JVM languages) supporting transparently WebSockets, Server Side Events (SSE), Long-Polling, HTTP Streaming (Forever frame) and JSONP. The Atmosphere Framework is portable and can be deployed on any Web Server that supports the Servlet Specification 2.3.

This post demonstrates how to create a “per session” Atmosphere Broadcaster. One that uniquely associates itself with a client’s  http session and forms this way some kind of durable unique “communication channel” between the server and the client. 

Keep reading

Database-driven message source in Spring

Typical Spring’s message source (see the MessageSource Javadoc) relies on the resource bundles. However it is quite easy to create a custom MessageSource implementation that determines messages from some other external data source.

This post demonstrates how to initialize a database-driven MessageSource and presents two approaches how messages can be saved in the database.

Keep reading

How to create Java POJOs dynamically at runtime with Javassist

Imagine your application have to create Java POJO instances dynamically at runtime from some external configuration. This task can be easily done using one of the  bytecode manipualtion library. This post demonstrates how this can be done using Javassist library.

Assume we have following configuration for the properties our dynamically created POJO should contain:

Map<String, Class<?>> props = new HashMap<String, Class<?>>();
props.put("foo", Integer.class);
props.put("bar", String.class);

Let’s write a PojoGenerator, that dynamically generates a Class object for the given class name and a map, containing required properties:

import java.io.Serializable;
import java.util.Map;
import java.util.Map.Entry;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;

public class PojoGenerator {

	public static Class generate(String className, Map<String, Class<?>>  properties) throws NotFoundException,
			CannotCompileException {

		ClassPool pool = ClassPool.getDefault();
		CtClass cc = pool.makeClass(className);

		// add this to define a super class to extend
		// cc.setSuperclass(resolveCtClass(MySuperClass.class));

		// add this to define an interface to implement
		cc.addInterface(resolveCtClass(Serializable.class));

		for (Entry<String, Class<?>> entry : properties.entrySet()) {

			cc.addField(new CtField(resolveCtClass(entry.getValue()), entry.getKey(), cc));

			// add getter
			cc.addMethod(generateGetter(cc, entry.getKey(), entry.getValue()));

			// add setter
			cc.addMethod(generateSetter(cc, entry.getKey(), entry.getValue()));
		}

		return cc.toClass();
	}

	private static CtMethod generateGetter(CtClass declaringClass, String fieldName, Class fieldClass)
			throws CannotCompileException {

		String getterName = "get" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);

		StringBuffer sb = new StringBuffer();
		sb.append("public ").append(fieldClass.getName()).append(" ")
				.append(getterName).append("(){").append("return this.")
				.append(fieldName).append(";").append("}");
		return CtMethod.make(sb.toString(), declaringClass);
	}

	private static CtMethod generateSetter(CtClass declaringClass, String fieldName, Class fieldClass)
			throws CannotCompileException {

		String setterName = "set" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);

		StringBuffer sb = new StringBuffer();
		sb.append("public void ").append(setterName).append("(")
				.append(fieldClass.getName()).append(" ").append(fieldName)
				.append(")").append("{").append("this.").append(fieldName)
				.append("=").append(fieldName).append(";").append("}");
		return CtMethod.make(sb.toString(), declaringClass);
	}

	private static CtClass resolveCtClass(Class clazz) throws NotFoundException {
		ClassPool pool = ClassPool.getDefault();
		return pool.get(clazz.getName());
	}
}

That’s it!

Using PojoGenerator is quite simple. Let’s generate some POJO, output via reflection all its methods, set and then get some property:

public static void main(String[] args) throws Exception {

	Map<String, Class<?>> props = new HashMap<String, Class<?>>();
	props.put("foo", Integer.class);
	props.put("bar", String.class);

	Class<?> clazz = PojoGenerator.generate(
			"net.javaforge.blog.javassist.Pojo$Generated", props);

	Object obj = clazz.newInstance();

	System.out.println("Clazz: " + clazz);
	System.out.println("Object: " + obj);
	System.out.println("Serializable? " + (obj instanceof Serializable));

	for (final Method method : clazz.getDeclaredMethods()) {
		System.out.println(method);
	}

	// set property "bar"
	clazz.getMethod("setBar", String.class).invoke(obj, "Hello World!");

	// get property "bar"
	String result = (String) clazz.getMethod("getBar").invoke(obj);
	System.out.println("Value for bar: " + result);

}

Executing above will result in the following console output:

Clazz: class net.javaforge.blog.javassist.Pojo$Generated
Object: net.javaforge.blog.javassist.Pojo$Generated@55571e
Serializable? true
public void net.javaforge.blog.javassist.Pojo$Generated.setBar(java.lang.String)
public java.lang.String net.javaforge.blog.javassist.Pojo$Generated.getBar()
public java.lang.Integer net.javaforge.blog.javassist.Pojo$Generated.getFoo()
public void net.javaforge.blog.javassist.Pojo$Generated.setFoo(java.lang.Integer)
Value for bar: Hello World!
Configuring Spring based Web Application from database or other external data source

The most common usecase to configure Spring’s application context using external properties is a combination of a property file and a PropertyPlaceholderConfigurer bean. If you deploy your application in multiple environments (e.g. development, pre-production, production..) it is a good idea to externalize this configuration file and to bring the application to load this file from external location on startup.

This post demonstrates how to replace the property file by other external data source (especially database) and make it possible to configure a Spring based web application on startup from it.

Keep reading

Generating boilerplate code with Maven and Groovy

In every project, there are frequently code fragments, one would like to generate on builtime instead to code by hand. This post demonstrates how to generate Java sources with Groovy as part of the Maven build lifecycle without much effort.

As an example I’ll take the RestyGWT interfaces from one of the previous posts (see GWT: Creating REST Services with Jersey and RestyGWT) and show how to generate them on build time.

Note! Using Groovy scripts it is possible to generate nearly any kind of required project sources / resouces.

Keep reading

MyBatis Generator Plugins

MyBatis is a data mapping framework providing capabilities to map SQL statements to Java Objects using Annotations or XML.

(Typical) Mapping rules can be written by hand or automatically generated by MyBatis Generator.

MyBatis Generator will generate:

  • SqlMap XML Files
  • Java Classes to match the primary key and fields of the table(s)
  • Java Client Classes that use the above objects (optional)

Furthermore it is possible to write custom plugins to enhance the generation process and to provide additional capabilities to generated sources.

Several months ago i’ve written some MyBatis Generator Plugins presented in this post. Check out the project’s source code on GitHub: https://github.com/bigpuritz/mybatis-generator-plugins

Keep reading

Configuring Logback programatically on web application startup

Logback is a successor of Log4J and a wonderful logging library to use in Java Applications.
Read about the reasons to prefer Logback over Log4j on this page.
This post describes just a simple usecase configuring Logback programmatically on Web Application startup.

Why should I want programmatic Logback configuration? Default Logback initialization (see Logback Manual) steps are:

  • Logback tries to find a file called logback.groovy in the classpath.
  • If no such file is found, logback tries to find a file called logback-test.xml in the classpath.
  • If no such file is found, it checks for the file logback.xml in the classpath..
  • If neither file is found, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.


Sometimes however you may want to read the configuration located outside your web application (e.g. somewhere in the filesystem, JNDI, database,…). This can be done by implementing a custom ServletContextListener, that does the job.

Here some sample code:

public class LogbackInitializer implements ServletContextListener {

	private static final Logger logger = LoggerFactory
			.getLogger(LogbackInitializer.class);

	private static final String logbackConfigSysProp = "app.logback.config.location";

	@Override
	public void contextInitialized(ServletContextEvent sce) {

		// init "Java Util Logging" bridge to forward JUL messages to SLF4J/Logback
		SLF4JBridgeHandler.install();
		
		// here we reading system property specifing the location of the 
// logback application's configuration file String logbackConfigLocation = System.getProperty(logbackConfigSysProp); if (logbackConfigLocation == null || logbackConfigLocation.isEmpty()) { sce.getServletContext().log( "WARNING! No logback configuration found! Please configure '" + logbackConfigSysProp + "' system property!"); } else { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); // Call context.reset() to clear any previous configuration, // e.g. default configuration. For multi-step configuration, // omit calling context.reset(). context.reset(); configurator.doConfigure(logbackConfigLocation); StatusPrinter.printInCaseOfErrorsOrWarnings(context); logger.info("Logback logger configured successfully..."); } catch (JoranException e) { sce.getServletContext().log("Error configuring logback!", e); } } } @Override public void contextDestroyed(ServletContextEvent sce) { logger.info("Destroying logback logger context..."); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.stop(); } }

Note! Logback already provides a pre-defined system property logback.configurationFile to specify the external location of the configuration file. However if you want to use application specific property name (in case of multiple web apps running in the same server instance) or provide a not file-based configuration (e.g. external URL, database…) this should be the best way to configure logback.

GWT: Creating REST Services with Jersey and RestyGWT

GWT-RPC is known to be a preferred way to implement client-server communication in GWT. Sometimes however it is a good idea to implement server-client communication using REST (e.g. backend services for non-GWT clients, application’s REST API for the world outside etc…)

In this small tutorial we’ll create a simple REST service with Jersey Framework on the serverside and a corresponding REST client with RestyGWT library on the clientside (GWT-side).

Check out the complete maven example project on GitHub: https://github.com/bigpuritz/javaforge-blog/tree/master/restgwt

First we need some domain model class:

public class Person {

    private int id;

    private String name;

    private Date dateOfBirth;

    public Person() {
    }

    public Person(int id, String name, Date dateOfBirth) {
        this.id = id;
        this.name = name;
        this.dateOfBirth = dateOfBirth;
    }

    // getter / setter goes here
}

Now let’s create Person’s REST resource using Jersey:

@Path("/person")
public class PersonResource {

    private static final Logger logger = LoggerFactory
            .getLogger(PersonResource.class);

    private static int counter = 1;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List getPersons() {

        List persons = new ArrayList();
        for (int i = 0; i < 5; i++) {
            persons.add(new Person(counter, "name-" + counter, new Date()));
            counter++;
        }

        logger.info("Returning {} persons...", persons.size());

        return persons;
    }

}

On each http request http://…../rest/person it will return 5 persons as JSON like this:

[
   {"id":1,"name":"name-1","dateOfBirth":1346268802016},
   {"id":2,"name":"name-2","dateOfBirth":1346268802016},
   {"id":3,"name":"name-3","dateOfBirth":1346268802016},
   {"id":4,"name":"name-4","dateOfBirth":1346268802016},
   {"id":5,"name":"name-5","dateOfBirth":1346268802016}
]

Last thing to be done on the serverside is a Jersey configuration in web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <servlet>
        <servlet-name>jersey-rest</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>net.javaforge.gwt.rest.server.remote.rest</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-rest</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <!-- Default page to serve -->
    <welcome-file-list>
        <welcome-file>App.html</welcome-file>
    </welcome-file-list>

</web-app>

Furthermore we need to create a REST client, that will be used as asynchronous remote service in our GWT classes. Writing a REST proxy with RestyGWT is fairly straightforward:

public interface PersonResourceAsync extends RestService {

    @GET
    void getPersons(MethodCallback<List> callback);

    /**
     * Utility class to get the instance of the Rest Service
     */
    public static final class Util {

        private static PersonResourceAsync instance;

        public static final PersonResourceAsync get() {
            if (instance == null) {
                instance = GWT.create(PersonResourceAsync.class);
                ((RestServiceProxy) instance).setResource(new Resource(
                        "rest/person"));
            }
            return instance;
        }

        private Util() {
            // Utility class should not be instantiated
        }
    }

}

Now we can write simple GWT EntryPoint that populates a table from the Person’s REST resource on button click:

public class App implements EntryPoint {

    private FlexTable personsTable;

    static {
        // if you don't do this, on JSON response you'll get something like
        // this:
        // "Could not parse response: org.fusesource.restygwt.client.ResponseFormatException: Response was NOT a valid JSON document"
        Defaults.setDateFormat(null);
    }

    @Override
    public void onModuleLoad() {

        Button button = new Button("load persons");
        button.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                loadPersons();
            }
        });

        personsTable = new FlexTable();
        personsTable.setCellPadding(1);
        personsTable.setCellSpacing(0);
        personsTable.setWidth("600px");

        RootPanel.get().add(button);
        RootPanel.get().add(personsTable);

    }

    private void loadPersons() {

        PersonResourceAsync.Util.get().getPersons(
                new MethodCallback<List>() {

                    @Override
                    public void onSuccess(Method method, List persons) {
                        if (personsTable.getRowCount() == 0) { // add header
                            personsTable.setText(0, 0, "ID");
                            personsTable.setText(0, 1, "NAME");
                            personsTable.setText(0, 2, "DATE OF BIRTH");
                            personsTable.getRowFormatter().addStyleName(0,
                                    "tableHeader");
                        }

                        for (Person p : persons) {
                            int rowNum = personsTable.getRowCount();
                            personsTable.setText(rowNum, 0,
                                    String.valueOf(p.getId()));
                            personsTable.setText(rowNum, 1, p.getName());
                            personsTable.setText(rowNum, 2,
                                    String.valueOf(p.getDateOfBirth()));
                        }
                    }

                    @Override
                    public void onFailure(Method method, Throwable exception) {
                        Window.alert("Error while loading persons! Cause: "
                                + exception.getMessage());
                    }
                });
    }
}