javawaveblogs-20

Monday, November 26, 2012

Restful webservice using CFX and Spring




1. Create a new Maven Web project using Netbeans IDE. (Version used for this post is 7.3 beta3)



2. Run through the wizard to create the Maven Web Application. here i have given the name "CFXSpring" as the project name.


3. In the next screen of the wizard select the server of your choice.  Here i have selected Glassfish server which comes bundled with Netbeans.


4. Then click on finish, your project is ready to use. Here you can notice the following folder structure is created by Maven for you.


5. Now its time to add Spring MVC Framework to our application. So right click on the project node in project window and go to properties menu item. IDE will pop up a properties window for you. In that window go to "Frameworks" categories.  In the right panel of the window you will get a empty text area with an "Add" button to its right. Just Click on the Add button.Another framework window will pop up with the list of frameworks works available to choose from.  Select Spring Web MVC from that window.  See the screen shot below for clarity.



6. Now select the Spring Framework version you like to use with this application.  Here i have selected 2.5.6 to use with my application.  see the figure below.


7. Once the above step is done.  Spring frame work will be added to the project by the IDE, by including the needed dependencies to the POM.XML file. By the way adding the dependencies to the project dependencies folder. see the figure below.


8. Now you can see there is a change in the project folder structure also.  A new folder "WEB-INF" is added to the project. That folder will also contain "applicationContext.xml" which is nothing but the Spring Configuration file where we will be wiring our beans and bean dependencies through property or constrructer injection. also you can see "web.xml" which is nothing but the web applications deployment descriptor.

9. In "web.xml" you can see already "org.springframework.web.servlet.DispatcherServlet" is configured for you by the IDE. so no need for us to do any extra configuration with respect to spring.

10. Now its time to add CFX dependencies to POM.XML.  This we will do manually with out using any of the IDE's wizards.

11. Open the "pom.xml" file which will be located in the projectfiles folder of the project.

12. Go to "dependencies" tag. and add the following dependency to it.

<dependency>             <groupId>org.apache.cxf</groupId>             <artifactId>cxf-rt-frontend-jaxrs</artifactId>             <version>2.6.2</version>         </dependency>

Wednesday, November 14, 2012

Camel-Jetty Step by Step using Netbeans IDE


Camel-Jetty Step by Step using Netbeans IDE
1. Create a Maven Java project using Netbeans IDE (Version used - 7.3 beta2)
  1. Go to New project wizard and Create a new maven java project
  2. Here for our sample the project is named as “MyHTTP”
  1. Click on finish
  2. now the IDE will create a Java Maven project for you with the recommended folder structure like below.
  1. Just check the POM.XML found inside the “ProjectFiles” folder. which will have the dependencies and plugin’s added automatically by the IDE. POM created for “MyHTTP” is shown below.
  1. Now its time to add Camel dependencies to our POM.XML file. add the following dependencies to your pom.xml file inside the dependencies tag.
        

       






















       
  1. Once the dependencies are added just clean and build your project. so that maven will download the required jar files listed in the dependencies tag to your project from the central repository. and also will pack the required JAR files to your “\MyHTTP\target\” path with name “MyHTTP-1.0-SNAPSHOT.jar”.
  2. Now in your project you can see a main class created with the name “App.java”.
  3. its time to edit the java class App.java and add the following code to it.
package com.mm.myhttp;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
/**
 *
 * @author Muthu
 */
public class App {
    public static void main(String[] args) {
        DefaultCamelContext camelContext = new DefaultCamelContext();
        try {
            camelContext.addRoutes(new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    from("jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true")
                            .process(new Processor() {
                        @Override
                        public void process(Exchange exchng) throws Exception {
                            System.out.println("Inside process exchange");
                            String body = exchng.getIn().getBody(String.class);
                            // this is the way to access HttpServletRequest
                            HttpServletRequest req =
                                    exchng.getIn().getBody(HttpServletRequest.class);
                            // send a html response back to client
                            exchng
                                    .getOut()
                                    .setBody(""
                                    + "Simple Demo for Camel-Jetty component"
                                    + "
");
                        }
                    });
                }
            });
            camelContext.start();
        } catch (Exception ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

  1. the important part of the code is “from("jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true")” from route which starts jetty server and listens to the http url mentioned in the from route.
  2. then the route flows to the process where a html response is set to the body and returned to the client.
  3. To test this application, just run the Java Maven project with App.java as the main class.
  1. In the Output window you can see the http service running at port 80. and our component uses Jetty-7.5.4 to run the service.
  1. Now hit the url(http://localhost/myapp/myservice/) using your browser and you should be able to see the html response back from the service.

Sunday, May 3, 2009

Convert a String to Lower Case in Java

Here this post will show you how to convert a string to lower case in Java.


String actualValue = "JAVA WAVE";

String lowerCase = actualValue.toLowerCase();

Monday, March 9, 2009

Generate a unique identifier with java.util.UUID

Java SE 5 has introduced the java.util.UUID class to easily generate Universally Unique Identifier (UUID)


import java.util.UUID;

/**
* This class is used to generate UUID and return it as a String object
*
* @author dhanago
*
*/
public class GenerateUUID
{
/**
* method to return UUID as a String object
*
* @return
*/
public static String getUUID()
{
return UUID.randomUUID().toString();
}
}

Tuesday, March 3, 2009

Java utility to read from resource bundle or properties file



/**
* dataSource.properties is loaded to a resource bundle.
*/
public static ResourceBundle resourceBundle = ResourceBundle.getBundle(
"sample.prop.health");

/**
* This method will return the value of the property from the resource
* bundle.
*
* @param key
* property key
* @return property value
*/
public static String getProperty(String key)
{
String value = null;
try
{
value = resourceBundle.getString(key);
}
catch (MissingResourceException missingResourceException)
{
Logger.getLogger(Utility.class.getName()).
log(Level.SEVERE,
"Resource Bundle not found",
missingResourceException);
}
return value;
}

Java method to format the current date to yyyy-MM-dd using SimpleDateFormat.


/**
* This method will format the current date to yyyy-MM-dd.
* @return
* current date as String.
*/
public static String formatedCurrentDate()
{
String toDate = new Date().toString();
SimpleDateFormat formatter = new SimpleDateFormat(
"EEE MMM yyyy hh:mm:ss zzz");
Date date = formatter.parse(toDate,
new ParsePosition(0));

toDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
return toDate;
}

Java method to return a File object from the file path specified


/**
* This method will return a file from the path specified.
*
* @param path
* path of the file name.
* @param fileName
* Name of the file.
* @return File object
*/
public static File readFileFromPath(String path, String fileName)
{
String fileNameWithPath = null;
if (path.endsWith("/"))
{
fileNameWithPath = path + fileName;
}
else
{
fileNameWithPath = path + "/" + fileName;
}
File file = new File(fileNameWithPath);

return file;
}

diggthis