JSF 2 + Jetty Example

JSF 2 + Jetty Example
In this example we will see how to setup a simple JSF project with jetty container.

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

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>
    </dependencies>

2. Update FacesServlet in to your web.xml

<listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

3. Create a managed bean

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;
@ManagedBean(name = "myFirstManagedBean", eager = false)
public class MyFirstManagedBean {
    public MyFirstManagedBean() {
          System.out.println("My bean");
       }
       public String getMessage() {
          return "Welcome to my jsf example";
       }
}

4. Create a xhtml file
Note: This is using JSF expression language to map the managed bean method

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>My JSF Examples</title>
</head>
<body>
   #{myFirstManagedBean.message}
</body>
</html>

5. Update jetty server and build details in to pom.xml

<build>
        <finalName>vinod-jsf</finalName>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.version}</version>
                <configuration>
                    <webAppConfig>
                        <contextPath>/${project.artifactId}</contextPath>
                        <overrideDescriptor>${override-web-xml}</overrideDescriptor>
                    </webAppConfig>
                    <stopKey>stop</stopKey>
                    <stopPort>8081</stopPort>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <version>2.9</version>
                    <configuration>
                        <wtpversion>2.0</wtpversion>
                        <downloadSources>true</downloadSources>
                        <additionalProjectFacets>
                            <jst.jsf>2.0</jst.jsf>
                        </additionalProjectFacets>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

6. Run it
mvn jetty:run
http://localhost:8080/vinod-jsf/myFirstJsf.xhtml







7. Done !! download example
https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-jsf

Could not find backup for factory javax.faces.context.FacesContextFactory

JSF startup issues
an 16, 2016 8:41:34 AM javax.faces.FactoryFinder$FactoryManager getFactory
SEVERE: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory. Attempting to find backup.
[WARNING] unavailable
java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.

Resolution
Add listener details in to your web.xml
<listener>

        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>

</listener>

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
 

Spring MVC + Standalone Jetty container example

Spring MVC + Jetty container example

1. Create a maven project 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>
 

2. Create  Spring configuration class

package com.vinod.vinod_spring_test;

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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
        "com.vinod.vinod_spring_test"})
public class SpringWebConfig extends WebMvcConfigurerAdapter {
         
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**").addResourceLocations("classpath:/files/");
        }
     
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("redirect:NewFile.html");
        }
}
 

3. Create a controller class 

package com.vinod.vinod_spring_test;

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

@Controller
public class MyController {
    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public String getHelloworld() {
        return "redirect:NewFile.html";
    }
}

4. Create html file 

Place this html file in to your src/main/resource/files folder (Create a directory named files)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello world
</body>
</html>

5. Create a stand alone class to configure and 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;

/**
 * Hello world!
 *
 */

public class App {
    public static void main(String[] args) {
        final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(SpringWebConfig.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();
        }
    }
}
 

6. Run it..

http://localhost:8080/helloworld

7. Download source code here

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-spring-web


Screen capture using java

Screen capturing using Java
java.awt.Robot,this class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.
Here is one example to capture the current screen using java.awt.Robot class.
package com.vinod.test;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.imageio.ImageIO;

public class JavaScreenCapture {

public static void main(String... args) throws Exception {
Robot robot = new Robot();
Rectangle rect = new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bImage = robot.createScreenCapture(rect);
String base64String = imgToBase64String(bImage, "png");
System.out.println(base64String);
}

public static String imgToBase64String(final RenderedImage img,
final String formatName) throws IOException {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
}
}
The output of this program will be a base64 String and use any online tool to generate it as image ..use http://codebeautify.org/base64-to-image-converter
Done !!

Java 8 Method Reference example

package com.vinod.test;

public class Java8ThreadExample {
public static void main(String[] args) {
Thread t1 = new Thread(Java8ThreadExample::printJob);
Thread t2 = new Thread(Java8ThreadExample::printJob);
t1.start();
t2.start();

}
public static void printJob() {
for (int i = 1; i <= 15; i++) {
System.out.println(Thread.currentThread()+"printing" + i);
}

}
}

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 
 
 

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts