Make Technology easier

Java

A unit testis 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.

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

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.

Create a custom package ws.example appropriately and include the TemperatureConverter.java file in that package. Compile and build the project.

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.

Select the Axis2 Service archiver and click Next. You will see the Axis2 service definition selection page.On 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.

After selecting the correct output location, click Next.After selecting the correct output location, click Next.
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.

Click NEXTThis 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.

For this example, we do not need any external libraries added to the generated service. Therefore, click Next to proceed to the next stepThis 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.

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.
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.

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.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.

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

But in this case we have to instantiate Triangleor a Circlewhen we need to access the draw method. Then there is an another approach to solve this problem using an Interfaceor an abstractclass. Following is the sample code.

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 Circleor 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.

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 Drawingclass as long as that class is a type of Shape. The drawing class doesn’t own the relationship of Shape types.

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:

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.

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.

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.

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.

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.

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”);