Archive

Archive for the ‘Java’ Category

Unit testing with JUnit

September 16, 2013 Leave a comment

final-logo

unit test is a piece of code written by a developer that executes a specific functionality in the code which is tested. The percentage of code which is tested by unit tests is typically called test coverage.

Unit tests target small units of code, e.g. a method or a class, (local tests) whereas component and integration tests targeting to test the behavior of a component or the integration between a set of components or a complete application consisting of several components.

Unit tests ensure that code works as intended. They are also very helpful to ensure that the code still works as intended in case you need to modify code for fixing a bug or extending functionality. Having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.

Typically unit tests are created in their own project or their own source folder to avoid that the normal code and the test code is mixed.

To integrate the unit testing to your application you need to use unit testing library. Here are couple of annotations used in the unit testing.

Annotation Description
@Test
public void method()
The annotation @Test identifies that a method is a test method.
@Before
public void method()
This method is executed before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
@After
public void method()
This method is executed after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
@BeforeClass
public static void method()
This method is executed once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@AfterClass
public static void method()
This method is executed once, after all tests have been finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Test (expected = Exception.class) Fails, if the method does not throw the named exception.
@Test(timeout=100) Fails, if the method takes longer than 100 milliseconds.

 

JUnit provides static methods in the Assert class to test for certain conditions. These assertion methods typically start with asserts and allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.

The following table gives an overview of these methods. Parameters in [] brackets are optional.

Statement Description
fail(String) Let the method fail. Might be used to check that a certain part of the code is not reached. Or to have a failing test before the test code is implemented.
assertTrue([message], boolean condition) Checks that the boolean condition is true.
assertsEquals([String message], expected, actual) Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays.
assertsEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object) Checks that the object is null.
assertNotNull([message], object) Checks that the object is not null.
assertSame([String], expected, actual) Checks that both variables refer to the same object.
assertNotSame([String], expected, actual) Checks that both variables refer to different objects.

Lets create a simple java application with the Junit integration.

First create the class which should be tested.

MyClass.java


package com.vogella.junit.first;

public class MyClass {

public int multiply(int x, int y){

 if(x>999){
 throw new IllegalArgumentException("X should be less than 1000");
 }

 return x*y;
 }
}

Then create a separate source folder to place the unit testing class to the application. This can be added by New->Junit class option in the eclipse.


package com.vogella.junit.first;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class MyClassTest {

@BeforeClass
 public static void testSetup() {

}

@AfterClass
 public static void testCleanup() {
 }

 @Test(expected=IllegalArgumentException.class)
 public void testExceptionIsThrown(){
 MyClass tester = new MyClass();
 tester.multiply(1000, 5);
 }

 @Test
 public void testMultiply() {
 MyClass tester = new MyClass();
 assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));
 }

}

Now run the application as a junit test.

jUNit

These results show that the MyClass.java functionalities are working properly.

Categories: Java, JUnit

Developing Web Services Using Apache Axis2

September 11, 2013 Leave a comment

These are the tools used in the tutorial.

1) Java Development Kit 1.4.2.x (Download)

2) Eclipse SDK 3.2.x (Download)

3) Apache Tomcat 4.1.x (Download)

4) Axis2 Web Application (Download)

5) Axis2 Eclipse Plugins (Download)

First download this two eclipse plugins and place them inside the dropins folder in eclipse. Other than the two plugins, we need the Axis2 runtime to deploy the developed Web services. We use the Axis2 Web Application which can be deployed in any popular servlet container. (You can download the Axis2 Web Application from the Axis2 Download page.) You have to just place it in the repository of the servlet container and run it. For example, if you are using Apache Tomcat, just copy the downloaded .war file, put it in the webapp folder, and start the servlet container.

PART 1 – The Bottom Up Approach in Web Services Development Using the Apache Axis2 Eclipse Plugin

  1. Start Eclipse SDK. First we need to create a JAVA project in Eclipse. (Follow the instruction on Eclipse SDK help.) You can give any name to the JAVA project, but for clarity, let us create a JAVA project called “TemperatureWebService”.In the Bottom Up Approach, we start with the service implementation and then build the deployable Web service component. We will be using the TemperatureConverter class definition as the logic for developing, deploying, and testing the Web service.
  2. Create a custom package ws.example appropriately and include the TemperatureConverter.java file in that package. Compile and build the project.
    package ws.example;
    
    /**
     * Temperature Converter Implementation Class
     */
    public class TemperatureConverter {
     /**
     * util method to convert Celsius to Fahrenheit
     * @param cValue : double value of celsius
     * @return calculated value of fahrenheit
     */
     public double c2fConvertion(double cValue) {
     return ((cValue * 9.0)/5.0 )+ 32.0;
     }
    
    /**
     * util method to convert fahrenheit to celsius
     * @param fValue : double value of fahrenheit
     * @return calculated value of celsius
     */
     public double f2cConvertion(double fValue) {
     return ((fValue - 32.0) * 5.0) / 9.0;
     }
    }
    
    
  3.  After successfully building the project, we will create the service archive using the Axis2 Eclipse Service Archiver Plugin. On the File menu, click New and then click Other to access the Axis2 wizards. Else, you can press Ctrl+N.
    Note : At any given time, you can go back through the wizards, change the settings, and even start the wizards all over again to create a different Web service on another JAVA project available in your workspace.image001
  4. Select the Axis2 Service archiver and click Next. You will see the Axis2 service definition selection page.image002On this page, select the output location of the “TemperatureWebService” Java project that we previously developed. Here we point to the service implementation classes. If there is more than one class, you only have to point to the JAVA project build location. The wizard includes all the implementation files. To be on the safe side, if you are going to expose a complex project as a Web service, it’s better to select the include .class files check box to omit unnecessary resource files that will increase the size of the deployable service archive that we are going to create.
  5. After selecting the correct output location, click Next.After selecting the correct output location, click Next.image003
    On this page, you can browse for the WSDL file. If you do not want to add a WSDL file to the service archive, select the Skip WSDL check box. Else you can select the Select WSDL check box, and specify the location of the WSDL file. We will skip the WSDL for the moment.
  6. Click NEXT
    image004This page is to add the libraries. The library name (with the full path) can be specified by either typing it or browsing for it. Once the library name with the full path is entered, click Add to add the library to the list. The added libraries should be displayed in the Added libraries list. You can add as many external libraries as you wish.If any added library has to be removed, select it from the Added libraries list and click Remove.
  7. For this example, we do not need any external libraries added to the generated service. Therefore, click Next to proceed to the next stepimage005This page is about the services.xml generation. If you have a custom services.xml file, you can select the services.xml file on this page by browsing for it or you can generate the service XML automatically. The browsing option is disabled when the Generate service xml automatically check box is selected.
  8. For this example, we use the automatically generated services.xml rather than a custom written one. Therefore, select the Generate service xml automatically check box, and then click Next.image006
    Note that this page will appear only if you selected to generate the services.xml automatically in the previous step. (If you selected a services.xml file, then you will be directed to the last page of the wizard.) After entering the correct service name and a valid fully qualified class name, load the existing methods of that class by clicking Load. If it is successfully loaded, you will see a table at the bottom of the page with the details of the loaded class. You can specify the methods to include in the services.xml by selecting the corresponding check boxes.
  9. Select the Search declared method only check box, to remove the inherited methods from the class. We do not need the inherited methods to be exposed and our only interest is in temperature conversion logic. Click Next to proceed to the last page of the wizard.image007
    On the last page of the wizard, specify the output file location and the output archive file name to complete the wizard. Note the location given in the example above. After specifying a name to identify the service that we will be deploying, we can directly guide the wizard to deploy this newly created Web service on any available Web service repository.Since we already have the Apache Axis2 Web application deployed on the servlet container, we can easily guide the wizard to deploy the service in the Axis2 Webapp (Axis2.war) inside Apache Tomcat. After deploying the Web application, the service repository will be available in the <TOMCAT_HOME>/webapp/axis2/WEB-INF/services folder.
  10. Click Finish to complete the steps in the wizard.
    image013
  11. Start the servlet container (in this case the Apache Tomcat), and navigate to http://localhost:8080/axis2 This will lead to the Axis2 Web application home page.image_b001image_b002
    Reference: http://wso2.com/library/1719

    SourceCode https://github.com/supun/TemperatureWebService

Categories: Java, Web Services, XML

Understanding Dependency Injection (DI)

spring_triangle

Suppose we have an application to do the drawings of different shapes. The following would be the traditional way of implementing it.

di_1

But in this case we have to instantiate Triangle or a Circle when we need to access the draw method. Then there is an another approach to solve this problem using an Interface or an abstract class. Following is the sample code.

package com.technodyne.common;

public abstract class Shape {

public abstract void draw();
}

Now add the following classes extending the Shape abstract class. 

package com.technodyne.common;

public class Circle extends Shape {

@Override
 public void draw() {
 // TODO Auto-generated method stub

 }

}

and


package com.technodyne.common;

public class Triangle extends Shape {

@Override
 public void draw() {
 // TODO Auto-generated method stub

 }

}

And here is the implementation class for the application.


package com.technodyne.common;

public class DiApplication {

public void drawAction(){

Shape shapeTriangle = new Triangle();
 shapeTriangle.draw();

Shape shapeCircle = new Circle();
 shapeCircle.draw();
 }
 }

But still we should do the instantiate of the Circle and Triangle objects. Therefore as a quick alternative, we can add the following method to do our task. This method doesn’t involve in any object creation. It just execute the draw method of the object which is passed to the method.


public void myDrawMethod(Shape shape){
 shape.draw();
 }

Inside this method we have removed the dependency of Circle or Triangle  objects. But still we need to pass the object to the method. Which means that somewhere in this code snippets, we have to do the instantiate. So the proper approach would be removing object creation from the class.

For that, a separate class can be used to execute the draw method.


package com.technodyne.common;

public class Drawing {

private Shape shape;

/**
 * @param shape the shape to set
 */
 public void setShape(Shape shape) {
 this.shape = shape;
 }

 public void drawShape(){
 this.shape.draw();
 }

}

This Drawing class doesn’t do the object creation. When we pass the triangle object to the Setter, it will execute the draw method inside the triangle class. this will allow to insert new objects to the Drawing class as long as that class is a type of Shape. The drawing class doesn’t own the relationship of Shape types.

Categories: AOP, Java, Spring

Java reflection in action

ReflectionInherited

Java reflection is all about examining and/or modifying the properties of an object in the run time. It’s important to note that reflection specifically applies to objects – so you need an object of a class to get information for that particular class.

Reflection in Java consists of 2 primary things that you should remember:

  1. Metadata. Metadata literally means data about the data. In this case, metadata means extra data that has to do with your Java program – like data about your Java classes, constructors, methods, fields, etc.
  2. Functionality that allows you to manipulate the metadata as well. So, functionality that would allow you to manipulate those fields, methods, constructors, etc. You can actually call methods and constructors using Java reflection – which is an important fact to remember.

This is the java class we need to get the details of.


package com.technodyne.org;

public class AppTest {

private int counter;

 public void printIt(){
 System.out.println("printIt() no param");
 }

 public void printItString(String temp){
 System.out.println("printIt() with param String : " + temp);
 }

 public void printItInt(int temp){
 System.out.println("printIt() with param int : " + temp);
 }

 public void setCounter(int counter){
 this.counter = counter;
 System.out.println("setCounter() set counter to : " + counter);
 }

 public void printCounter(){
 System.out.println("printCounter() : " + this.counter);
 }
}

And then add this class to get the reflection of appTest class.


package com.technodyne.org;

import java.lang.reflect.Method;
public class ReflectApp {

public static void main(String[]args){

 //no paramater
 Class noparams[] = {};

 //String parameter
 Class[] paramString = new Class[1];
 paramString[0] = String.class;

 //int parameter
 Class[] paramInt = new Class[1];
 paramInt[0] = Integer.TYPE;

 try {
 //load the AppTest at runtime
 Class cls = Class.forName("com.technodyne.org.AppTest");
 Object obj = cls.newInstance();

 //call the printIt method
 Method method = cls.getDeclaredMethod("printIt", noparams);
 method.invoke(obj, null);

 //call the printItString method, pass a String param
 method = cls.getDeclaredMethod("printItString", paramString);
 method.invoke(obj, new String("technodyne"));

 //call the printItInt method, pass a int param
 method = cls.getDeclaredMethod("printItInt", paramInt);
 method.invoke(obj, 123);

 //call the setCounter method, pass a int param
 method = cls.getDeclaredMethod("setCounter", paramInt);
 method.invoke(obj, 999);

 //call the printCounter method
 method = cls.getDeclaredMethod("printCounter", noparams);
 method.invoke(obj, null);

 } catch (Exception e) {
 // TODO: handle exception
 e.printStackTrace();
 }
 }
}

Here is the result.

printIt() no param
printIt() with param String : technodyne
printIt() with param int : 123
setCounter() set counter to : 999
printCounter() : 999

You can find the sourcecode from below repo :)

https://github.com/supun/Reflection

Categories: Java Tags: ,

java web application with spark + freemarker + mongodb

Technologies used.

  •  Maven
  • Spark framework
  • Freemarker template engine
  • Java 1.7
  • MongoDB

First create a project template using maven. This project is the one i am following in the Mongodb for Java developers course conducted by 10gen.

After creating the project, edit the pom.xml as follows.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

<groupId>10gen</groupId>
 <artifactId>M101J</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>jar</packaging>

<name>M101J</name>
 <url>http://maven.apache.org</url>

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
 <repositories>
 <repository>
 <id>Spark repository</id>
 <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
 </repositories>
 <dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>com.sparkjava</groupId>
 <artifactId>spark-core</artifactId>
 <version>0.9.9.7-SNAPSHOT</version>
</dependency>
<dependency>
 <groupId>org.freemarker</groupId>
 <artifactId>freemarker</artifactId>
 <version>2.3.19</version>
</dependency>
 <dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>2.2</version>
</dependency>

 </dependencies>
</project>

Now create a separate resources folder and add the hello.ftl template file inside it.


<html>
<head>
 <title>Welcome!</title>
 </head>
<body>
<h1>Hello ${name}</h1>
</body>
</html>

Spark is mini java framework which is run on jetty server.

Now add the following java class.


package tengen;

import java.io.StringWriter;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;

import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class HelloWorldMongoDBfreemarkerStyle {

/**
 * @param args
 * @throws UnknownHostException
 * @throws MongoException
 */
 public static void main(String[] args) throws MongoException, UnknownHostException {
 // TODO Auto-generated method stub

final Configuration configuration = new Configuration();
 configuration.setClassForTemplateLoading(HelloWorldfreemarkerstyle.class, "/");
 Mongo client = new Mongo(new ServerAddress("localhost",27017));

 DB database = client.getDB("foo");
 final DBCollection collection = database.getCollection("foo");
 Spark.get(new Route("/") {

 @Override
 public Object handle(final Request request, final Response response) {
 StringWriter writer = new StringWriter();
 try {
 // TODO Auto-generated method stub
 Template helloTemplate = configuration.getTemplate("hello.ftl");

 DBObject document = collection.findOne();
 helloTemplate.process(document, writer);

 System.out.println(writer);
 } catch (Exception e) {
 // TODO: handle exception
 e.printStackTrace();
 }

 return writer;
 }
 });
 }

}

Now run the mongodb server. Then run the above java file. Go to localhost:4567 address in your browser. You will see “Hello MongoDB”.

PS.

there should be a collection named “foo” and inside that the following document.

{“name”:”MongoDB”} :)

Categories: Java, Jetty, mongodb, NOSQL

How To Create A Jar File With Maven

This post is about how to create a java project template into jar package. Here are the tools i have used.

  1. JDK 1.6
  2. Apache maven 3
  3. Eclipse 3.7

First create a project template using maven

$ mvn archetype:generate -DgroupId=com.supun.core -DartifactId=technodyne-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Then convert it to eclipse project.

cd technodyne/
mvn eclipse:eclipse

import it to Eclipse. Will show as follows.

The pom.xml file should be like this.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.supun.core</groupId>
 <artifactId>technodyne</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>technodyne</name>
 <url>http://maven.apache.org</url>

 <properties>
 <jdk.version>1.6</jdk.version>
 <log4j.version>1.2.17</log4j.version>
 </properties>

 <dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>${log4j.version}</version>
 </dependency>
 </dependencies>
 <build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compile-plugin</artifactId>
 <version>2.3.2</version>
 <configuration>
 <source>${jdk.version}</source>
 <target>${jdk.version}</target>
 </configuration>
 </plugin>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-jar-plugin</artifactId>
 <version>2.4</version>
 <configuration>
 <archive>
 <manifest>
 <addClasspath>true</addClasspath>
 <mainClass>com.supun.core.App</mainClass>
 <classpathPrefix>dependency-jars</classpathPrefix>
 </manifest>
 </archive>
 </configuration>
 </plugin>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-dependency-plugin</artifactId>
 <version>2.5.1</version>
 <executions>
 <execution>
 <id>copy-dependencies</id>
 <phase>package</phase>
 <goals>
 <goal>copy-dependencies</goal>
 </goals>
 <configuration>
 <includeGroupIds>log4j</includeGroupIds>
 <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
 </configuration>
 </execution>
 </executions>
 </plugin>
 </plugins>
 </build>
</project>

Then add the log4j dependencies for the project.


package com.supun.core;

import org.apache.log4j.Logger;

/**
 * Hello world!
 *
 */
public class App
{

 static Logger logger = Logger.getLogger(App.class);
 public static void main( String[] args )
 {
 System.out.println( "Hello World!" );

 if(logger.isDebugEnabled()){
 logger.debug("Testing");
 }
 }
}

Then create log4j.properties file inside the main/resources folder

# Root logger option
log4j.rootLogger=DEBUG, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

Now run this jar as follows.

 

That’ s it. Happy coding ..:D

Categories: Apache, build tools, Java, Maven, XML

Fixing Error – Importing Maven projects".Unsupported IClasspathEntry kind=4

September 12, 2012 4 comments

When i am working with eclipse, I tried to import a project using maven.

Before importing the project, it should be converted into eclipse project
  mvn eclipse: eclipse
Then i found the following error.
An internal error occurred during: “Importing Maven projects”.Unsupported IClasspathEntry kind=4
This bug is being discussed in  here.

<classpathentry kind="var" path="M2_REPO/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar">
</classpathentry>

Where is the value kind = “var” that M2E does not recognize and therefore throws the error.

Now type this.
mvn eclipse: clean

Now refresh the project in eclipse or re-import.

Categories: eclipse, Java

Getting Started with Maven and Spring

September 10, 2012 Leave a comment

What is Maven ?

Apache Maven originated as an attempt to simplify the build process for the now defunct Apache Jakarta Alexandria project. Its formative years were then spent in the Apache Turbine project where it eventually came to replace a brittle and fragile build system based on  Apache ANT.

First verify the  installation.

First create a sample application using maven.

$ mvn archetype:generate –batch-mode

  -DarchetypeArtifactId=maven-archetype-quickstart  
  -DgroupId=com.supun.spring 
  -DartifactId=spring-hello 
  -Dversion=1.0-SNAPSHOT
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

Here is the App class which is generated by Maven.

package com.supun.spring;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

Then add the following to the pom.xml

<build>
 <plugins>
 <plugin>
 <groupid>org.codehaus.mojo</groupid>
 <artifactid>exec-maven-plugin</artifactid>
 <executions>
 <execution>
 <goals>
 <goal>java</goal>
 </goals>
 </execution>
 </executions>

 <configuration>
 <mainclass>com.supun.spring.App</mainclass>
 </configuration>
 </plugin>
 </plugins>
 </build>

Now compile the project using mvn compile and run using mvn exec:java . Here is the output.

Now add the Spring dependencies to the project.

<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring</artifactid>
 <version>2.5.5</version>
</dependency>

Then, when we compile the project, the spring jars will be downloaded automatically. Now create a new class inside the spring-hellosrcmainjavacomsupun  folder as follows.

package com.supun;

public class SayHello
{

  private String name;

  public void setName(String name)
  {
    this.name = name;
  }

  public String getName()
  {
    return name;
  }

  public void greet()
  {
    System.out.println("Hello " + getName());
  }

}

Now add application-context.xml file to configure the spring beans. This should be placed inside the resources folder. src/main/resources
Then change the App.java class as follows.

package com.supun.spring;

import com.supun.SayHello;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
/**
 * Hello world!
 *
 */

public class App
{
    public static void main( String[] args )
    {
      BeanFactory factory = new XmlBeanFactory(
          new ClassPathResource("application-context.xml"));

      SayHello hello = (SayHello) factory.getBean("hello");
      hello.greet();
    }
}

Then clean and compile the project. Then run it. The output as following.

...

[INFO] [exec:java]
....
INFO: Loading XML bean definitions from class path resource [application-context.xml]
Hello Supun
Categories: AOP, Apache, Java, Spring

Add your Java web application to Jetty Server

What is Jetty Server ?

Jetty  is a pure Java-based HTTP server and servlet container (application server). Jetty is a free and open source project under the Apache 2.0 License. Jetty deployment focuses on creating a simple, efficient, embeddable and pluggable web server. Jetty’s small size makes it suitable for providing web services in an embedded Java application. It also offers support for Web Sockets, OSGi, JMX, JNDI, JASPI, AJP, and other Java technologies. ( Wikipedia).

Lets first create a sample web app using maven. Then deploy it to jetty server using maven-jetty plugin.

Generate the testWebApp using following command in the cmd.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp -DartifactId=testWebApp -DgroupId=net.supun.maven -Dversion=1.0-SNAPSHOT -Dpackage=net.supun.maven

Here is the output.

Then open the pom.xml file and add the following lines to it.


<build>

<finalname>testWebApp</finalname>
 <plugins>
 <plugin>
 <artifactid>maven-compiler-plugin</artifactid>
 <configuration>
 <source>1.6
 <target>1.6</target>
 </configuration>
 </plugin>
 </plugins>
 </build>

Then compile and install the project using Maven.
mvn compile
mvn test
mvn install

Then the file named index.jsp has created with the following content.

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

Now, add the jetty plugin in your pom.xml.

<plugin>
 <groupid>org.mortbay.jetty</groupid>
 <artifactid>maven-jetty-plugin</artifactid>
 <version>6.1.17</version>
 </plugin>

Now run the jetty server
mvn jetty:run
Then go to localhost:8080/testWebApp in your browser. The following will be the output.

Categories: Apache, Java, Jetty, Maven

Storing images in your documentDB – MongoDB

MongoDB has special API called GridFS to manipulate the files. It stores the files as bit chunks with 256k. Then we can retrieve the bit sequence to a image again. Keep remember to create a separate namespace to store these image files. I have used a namespace called photo – GridFS gfsPhoto = new GridFS(db,”photo”);
Here is the Java code on how to store an image and retrieve it.
package com.technodyne.core;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class SaveImage {

	public static void main(String[]args){

		try {

			Mongo mongo = new Mongo("127.0.0.1",27017);
			DB db = mongo.getDB("imagedb");
			DBCollection collection = db.getCollection("dummyImageCollection");

			String newFileName = "technodyne-java-image";
			File imageFile = new File("C:UsersSUPUNDesktopimages.jpg");

			GridFS gfsPhoto = new GridFS(db,"photo");
			try {
				GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
				gfsFile.setFilename(newFileName);
				gfsFile.save();

				DBCursor cursor = gfsPhoto.getFileList();
				while(cursor.hasNext()){
					System.out.println(cursor.next());
				}

				GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
				imageForOutput.writeTo("C:UsersSUPUNDesktopjava-monngo-image.jpg");
			    gfsPhoto.remove(gfsPhoto.findOne(newFileName));

			    System.out.println("Done");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (UnknownHostException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		catch(MongoException e){
			e.printStackTrace();
		}
	}
}
Categories: Java, JSON, mongodb, NOSQL
Follow

Get every new post delivered to your Inbox.