Showing posts with label Web Services. Show all posts
Showing posts with label Web Services. Show all posts

Spring ReSTful Web services + Jetty container

Spring ReSTful Web services + Jetty container
 
This is very simple example to create a web services using Spring and deploying in to Jetty container
 
1. Create a maven project and add below dependencies
 
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
    </dependencies>
 
2. Create a service class
 
package com.vinod;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/state")
public class MySpringService {
    @RequestMapping(value = "/{code}", method = RequestMethod.GET)
    public @ResponseBody String getState(@PathVariable String code) {
        String result;
        if (code.equals("KL")) {
            result = "Kerala";
        } else {
            result = "Default State";
        }
        return result;
    }
}
 
 
3. Create Spring configuration class
 
package com.vinod;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@ComponentScan(basePackages = { "com.vinod" })
public class SpringConfig {

}
 
 
4. Create a main class to start Jetty server.
 
package com.vinod;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class MyMain {
    public static void main(String[] args) {
        final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(SpringConfig.class);
        final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext));
        final ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(servletHolder, "/*");
        final Server server = new Server(8080);
        server.setHandler(context);
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            server.destroy();
            e.printStackTrace();
        }
    }

}
 
 
5. Run the application..
 
 
6. Done!! download examples
 

JAX-RS HttpHeaders

JAX-RS - how to get http headers in the service
In this example we will see how to get the http headers whenever JAX-RS provider receives http request.
package com.vinod.vinod_rest_examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
@Path("/request")
public class MyhttpHeaders {
/**
*http://localhost:8080/request/httpHeaders
*@param headers
*@return
*/
@GET
@Path("httpHeaders")
@Produces(MediaType.APPLICATION_JSON)
public String test(@Context HttpHeaders headers) {
return headers.getHeaderString("user-agent");
}
}
Hit the url 
http://localhost:8080/request/httpHeaders
 
Output !!!
 
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

JAX-RS Data binding examples

JAX-RS Binding values to method parameters

To call any service we need to bind the request to the resource method, in order to bind this JAX-RS has provided few parameter types, the data will be taken from these parameters by using the annotaions. Whenever JAX-RS provider receives an http request, it finds an appropriate java method  that can service this request.
Here are the parameters provided by JAX-RS API
 
            Query parameters
            URI path parameters
            Header parameters
            Form parameters
            Cookie parameters
            Matrix parameters
            Bean Parameters
 
In this example we will see how to use all these parameters.

1. Create a maven project using the quick start archetype and add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>

2. Create a simple service which uses all these params

package com.vinod.vinod_rest_examples;


import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;


@Path("/DataBinding")

public class DataBinding {

/**
    *http://localhost:8080/DataBinding/queryParam?name=vinod
    *
    *@param name
    *@return
    */
@GET
@Path("queryParam")
@Produces(MediaType.APPLICATION_JSON)
public String queryParam(@QueryParam("name") String name) {
return "Hello world " + name;
}

/**
    *http://localhost:8080/DataBinding/vinod/pathParam
    *
    *@param name
    *@return
    */
@GET
@Path("{name}/pathParam")
@Produces(MediaType.APPLICATION_JSON)
public String pathParam(@PathParam("name") String name) {
return "Hello world " + name;
}

/**
    *http://localhost:8080/DataBinding/headerParam
    *
    *@param userAgent
    *@return
    */
@Path("headerParam")
@GET
@Produces(MediaType.APPLICATION_JSON)

public String headerParam(@HeaderParam("user-agent") String userAgent) {
return "Hello world " + userAgent;
}

/**
    *http://localhost:8080/DataBinding/matrixParam;name=vinod;address=
    * bangalore
    *
    *@param name
    *@param address
    *@return
    */
@Path("matrixParam")
@GET
@Produces(MediaType.APPLICATION_JSON)

public String matrixParam(@MatrixParam("name") String name, @MatrixParam("address") String address) {
return "Hello world " + name + " " + address;
}

/**
    *http://localhost:8080/DataBinding/formParam pass the name in the form
    * request
    *
    *@param name
    *@return
    */
@Path("formParam")
@POST
public String formParam(@FormParam("name") String name) {
return "Hello world " + name;
}
}
 
3. Create a java class to start jetty server
package com.vinod.vinod_rest_examples;


import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;


/**
 * Hello world!
 *
 */
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

Server jettyServer = new Server(8080);
jettyServer.setHandler(context);

ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);

// Setting pacakge name over here to load services
jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "com.vinod.vinod_rest_examples");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}

4. Hit the urls for testing

http://localhost:8080/DataBinding/queryParam?name=vinod
http://localhost:8080/DataBinding/vinod/pathParam
http://localhost:8080/DataBinding/headerParam
http://localhost:8080/DataBinding/matrixParam;name=vinod;address=bangalore
http://localhost:8080/DataBinding/formParam pass the name in the form
 
Download this example!! https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-rest-examples 
 
 

JAX-RS RESTFul Service with Jetty server

In this example we will see simple JAX-RS restful web service using Jetty service and Jersey implementaion of JAX-RS API

1. Create a maven project using the quick start archetype.

2. Add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
3. Create a simple service class which returns Hello world
package com.vinod.vinod_rest_examples;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/MyFirstRest")
public class MyFirstRest {

@GET
@Path("helloworld")
@Produces(MediaType.APPLICATION_JSON)
public String test() {
return "Hello world";
}
}
4. Create a java class to start jetty server
package com.vinod.vinod_rest_examples;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

/**
 * Hello world!
 *
 */
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

Server jettyServer = new Server(8080);
jettyServer.setHandler(context);

ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);

// Setting pacakge name over here to load services
jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
"com.vinod.vinod_rest_examples");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
5. Hit the url
 
6. Output
Hello world

 
8. What is next?.. let us see how to add Request Filter over here.
Filters can modify inbound and outbound requests and responses such as modification of headers, entity and other request/response parameters
package com.vinod.vinod_rest_examples;

import java.io.IOException;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;

@Provider
@Priority(value = 1)
public class MyRequestFilter implements ContainerRequestFilter {

public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println("Executing request filter" + requestContext.getUriInfo().getPath());
}

}
filter output

Executing request filter/MyFirstRest/helloworld

 

Spring Restful Web Services + JAXB Example

Spring frameworks provides the Restful web services implementation, here is one simple example to implement Web services using Spring and uses JAXB for response binding.

Softwares Used

  • Java 1.8
  • Spring 4
  • Jetty Server


Create a maven project using web-app archetype and add below dependencies

<dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        

Create a Controller class to define our service
 
package com.vinod.vinod_spring_test;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mystate")
public class JaxbController {
    @RequestMapping(value = "/{code}", method = RequestMethod.GET)
    public State getState(@PathVariable String code) {
        String result;
        if (code.equals("KL")) {
            result = "Kerala";
        } else {
            result = "Default State";
        }
        State st = new State();
        st.setCode(code);
        st.setName(result);
        return st;

    }
}

State.java

package com.vinod.vinod_spring_test;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement(name = "state")
@XmlAccessorType(XmlAccessType.NONE)
public class State {
    @XmlElement(name = "name")
    private String name;
    @XmlElement(name = "code")
    private String code;

    //Getters and setters
}

Spring configuration class

package com.vinod.vinod_spring_test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {
        "com.vinod.vinod_spring_test"})
public class MyWebServiceSpringConfig{

}

Main class to start Jetty server

package com.vinod.vinod_spring_test;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class JettyWebserviceStart {

    public static void main(String[] args) {
        final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(MyWebServiceSpringConfig.class);
        final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext));
        final ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(servletHolder, "/*");
        final Server server = new Server(8080);
        server.setHandler(context);
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            server.destroy();
            e.printStackTrace();
        }
    }

}
  

Output

Run the above program and hit the below url

http://localhost:8080/mystate/KL




Download examples

https://github.com/kkvinodkumaran/spring

Spring Restful Web Services Example

Spring frameworks provides the Restful web services implementation, here is one simple example to implement Web services using Spring.

Softwares Used

  • Java 1.8
  • Spring 4
  • Jetty Server


Create a maven project using web-app archetype and add below dependencies

<dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.0</version>
        </dependency>
Create a Controller class to define our service
package com.vinod.vinod_spring_test;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/state")
public class StateController {
    @RequestMapping(value = "/{code}", method = RequestMethod.GET)
    public @ResponseBody String getState(@PathVariable String code) {
        String result;
        if (code.equals("KL")) {
            result = "Kerala";
        } else {
            result = "Default State";
        }
        return result;
    }
}
  


Spring configuration class

package com.vinod.vinod_spring_test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {
        "com.vinod.vinod_spring_test"})
public class MyWebServiceSpringConfig{

}


Main class to start Jetty server

package com.vinod.vinod_spring_test;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class JettyWebserviceStart {

    public static void main(String[] args) {
        final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(MyWebServiceSpringConfig.class);
        final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext));
        final ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(servletHolder, "/*");
        final Server server = new Server(8080);
        server.setHandler(context);
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            server.destroy();
            e.printStackTrace();
        }
    }

}
  


Output

Run the above program and hit the below url
http://localhost:8080/state/KL


Download examples

https://github.com/kkvinodkumaran/spring

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts