servlet Posts

Beginning REST Using JBoss RESTEasy

On today’s demo im trying to use RESTEasy to handle multiple REST requests. According to Wikipedia, REST (Representational state transfer) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. While RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS specification. JAX-RS is a new JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

On this project, im trying to create 2 different services. 1 service to get all objects, while another one for fetching a single objects. I create 2 different responses type for each service, JSON and XML. Okay, so lets try with 2 simple javabeans.

package com.edw.bean;

import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {

    private String name;
    private String address;
    private int age;

    @XmlElement(name="book")
    @XmlElementWrapper(name = "books")
    private List<Book> books;

    public Student() {
    }

    public Student(String name, String address, int age, List<Book> books) {
        this.name = name;
        this.address = address;
        this.age = age;
        this.books = books;
    }

	// other setter getter

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", address=" + address + ", age=" + age + ", books=" + books + '}';
    }
}
package com.edw.bean;

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

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {

    private String title;
    private double price;

    public Book() {
    }

    public Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

	// other setter getter

    @Override
    public String toString() {
        return "Book{" + "title=" + title + ", price=" + price + '}';
    }
}

Now, you need to create a java class to handle all REST services,

package com.edw.rest;

import com.edw.bean.Book;
import com.edw.bean.Student;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/service/student")
public class StudentRest {

    @GET
    @Path("/json")
    @Produces(MediaType.APPLICATION_JSON)
    // path would be http://localhost:8080/YourProject/service/student/json
    public List<Student> getStudentsJSON() {
        return getStudents();
    }

    @GET
    @Path("/xml")
    @Produces(MediaType.APPLICATION_XML)
    // path would be http://localhost:8080/YourProject/service/student/xml
    public List<Student> getStudentsXML() {
        return getStudents();
    }

    @GET
    @Path("/json/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    // path would be http://localhost:8080/YourProject/service/student/json/insertyournamehere
    public Student getStudentJSON(@PathParam("name") String name) {
        return new Student(name, name + " Address", 10, getBooks());
    }

    @GET
    @Path("/xml/{name}")
    @Produces(MediaType.APPLICATION_XML)
    // path would be http://localhost:8080/YourProject/service/student/xml/insertyournamehere
    public Student getStudentXML(@PathParam("name") String name) {
        return new Student(name, name + " Address", 10, getBooks());
    }

    private List<Book> getBooks() {
        List<Book> books = new ArrayList<Book>();
        books.add(new Book("Harry Potter", 100d));
        books.add(new Book("Lord of the Ring", 120d));
        books.add(new Book("Chicken Soup", 20d));
        books.add(new Book("Doraemon", 190d));
        books.add(new Book("Laskar Pelangi", 200d));
        return books;
    }

    private List<Student> getStudents() {
        List<Student> students = new ArrayList<Student>();
        students.add(new Student("Edwin", "Jakarta", 25, getBooks()));
        students.add(new Student("Kamplenk", "Ciledug", 29, getBooks()));
        students.add(new Student("Tebek", "Pamulang", 38, getBooks()));
        students.add(new Student("Syamsu", "Bandung", 60, getBooks()));
        return students;
    }
}

And dont forget to register your service class

package com.edw.config;

import com.edw.rest.StudentRest;
import java.util.Set;
import java.util.HashSet;
import javax.ws.rs.core.Application;

public class ApplicationConfig extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public ApplicationConfig() {
        singletons.add(new StudentRest());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

And last, register all in your web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.edw.config.ApplicationConfig</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Here are some screenshots,

Have fun with RESTEasy ;)

Google+

How to Create a Simple Servlet to Handle JSon Requests

On this example, im trying to create a simple servlet to handle JSon request. Im using this servlet to handle JSon request from my front end such as web or even desktop application. Thanks to GSon library, it really helped on simplifying javabean convert to json strings and the other way around.

First as usual, a simple java bean to handle request and response format

package com.edw.bean;

public class Student {
 
    private String name;
    private int age;
    private byte gender;

	// other setter and getter
}
package com.edw.bean;

public class Status {
    private boolean success;
    private String description;
	
	// other setter and getter
}

And this is my servlet,

package com.edw.servlet;

import com.edw.bean.Status;
import com.edw.bean.Student;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonParserServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");        
        Gson gson = new Gson();

        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }

            Student student = (Student) gson.fromJson(sb.toString(), Student.class);

            Status status = new Status();
            if (student.getName().equalsIgnoreCase("edw")) {
                status.setSuccess(true);
                status.setDescription("success");
            } else {
                status.setSuccess(false);
                status.setDescription("not edw");
            }
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            Status status = new Status();
            status.setSuccess(false);
            status.setDescription(ex.getMessage());
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        } 
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

This is a screenshot on how my message actually look like

Have Fun (H)

Google+

Get Absolute File Path Using ServletFilter

It’s all begin when i need to get a text file content from a servlet filter, after spent some amount of time googling i’ve found a good solution. This is how i do it.

package com.edw.filter;

import java.io.File;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class MyFilter implements Filter {

    private FilterConfig filterConfig = null;
    private Logger logger = Logger.getLogger(this.getClass());

    public MyFilter() {
        
    }    

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {
	
	try {
		String pathName = filterConfig.getServletContext().getRealPath("/");
		File file = new File(pathName);

		logger.debug(file.getAbsolutePath());

		chain.doFilter(request, response);
	}
	catch(Throwable t) {
	    logger.error(t,t);
	}
    }    

    public void destroy() { 
    }

    public void init(FilterConfig filterConfig) { 
		this.filterConfig = filterConfig;
    }    

}

Hope it can help others, thank you (*)

Google+

Beginning MyBatis : DataSource, JNDI and Apache DBCP

In this tutorial, im trying to connect a servlet to mysql database using Apache DBCP. Im using mybatis and accessing Apache DBCP’s datasource via JNDI. Btw, im using Netbeans 6.9 and Apache Tomcat 6.

First as always, a table named “contoh” on a database “test”

CREATE
    TABLE contoh
    (
        nama VARCHAR(30) NOT NULL,
        alamat VARCHAR(100),
        PRIMARY KEY (nama)
    )

insert into contoh (nama, alamat) values ('edwin', 'singapore');
insert into contoh (nama, alamat) values ('kamplenk', 'ciledug');
insert into contoh (nama, alamat) values ('nugie', 'pamulang');
insert into contoh (nama, alamat) values ('samsu', 'dago');
insert into contoh (nama, alamat) values ('tebek', 'karawaci');	

and a simple java bean

package com.edw.mybatis.bean;

import java.io.Serializable;

public class Contoh implements Serializable {
    private String nama;
    private String alamat;

	// other setter and getter
	
    @Override
    public String toString(){
        return nama+" : "+alamat;
    }
}

next is creating a simple xml query, ContohMapper.xml.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.edw.mybatis.mapper.ContohMapper" >

    <resultMap id="ContohMap" type="com.edw.mybatis.bean.Contoh" >
        <id column="nama" property="nama" jdbcType="VARCHAR" />
        <result column="alamat" property="alamat" jdbcType="VARCHAR" />
    </resultMap>
    

    <select id="selectAll" resultMap="ContohMap">
        SELECT * FROM contoh
    </select>

</mapper>

and an interface class to map my queries

package com.edw.mybatis.mapper;

import com.edw.mybatis.bean.Contoh;
import java.util.List;

public interface ContohMapper {    
    List<Contoh> selectAll();
}

Dont forget to create a connection pooling configuration on context.xml, which located under META-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/MyBatisDBCP">
    
    <Resource name="jdbc/test" auth="Container"
            type="javax.sql.DataSource"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/test"
            username="root"
            password="xxxx"
            maxActive="100" maxIdle="30" maxWait="10000"
            removeAbandoned="true"
            removeAbandonedTimeout="60"
            logAbandoned="true"
            />
            
</Context>

an xml configuration, Configuration.xml. This is where i put my connection properties.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="JNDI">
                <property name="data_source" value="java:/comp/env/jdbc/test"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/edw/mybatis/xml/ContohMapper.xml" />
    </mappers>
</configuration>

and a singleton class to load my configuration class,

package com.edw.mybatis.config;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/**
 *
 * @author edw
 */
public class MyBatisSqlSessionFactory {

    protected static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/mybatis/xml/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;
    }
}

and a simple servlet to call mybatis query

package com.edw.servlet;

import com.edw.mybatis.bean.Contoh;
import com.edw.mybatis.config.MyBatisSqlSessionFactory;
import com.edw.mybatis.mapper.ContohMapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class MainServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(MainServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();

            ContohMapper contohMapper = session.getMapper(ContohMapper.class);
            List<Contoh> contohs = contohMapper.selectAll();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>DBCP Example MainServlet</title>");
            out.println("</head>");
            out.println("<body>");
            
            for (Contoh contoh : contohs) {
                out.println(contoh.getNama()+" "+contoh.getAlamat()+"<br />");
                logger.debug(contoh.getNama()+" "+contoh.getAlamat());
            }

            out.println("</body>");
            out.println("</html>");

        }catch(Exception ex){
            logger.error(ex.getMessage(), ex);
            out.println(ex.getMessage());
        } finally {
            out.close();
        }
    } 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}

and dont forget to register your jndi and servlet to web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Session -->
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <!-- Welcome file -->
    <welcome-file-list>
        <welcome-file>mainServlet</welcome-file>
    </welcome-file-list>

    <!--  Servlet -->
    <servlet>
        <servlet-name>mainServlet</servlet-name>
        <servlet-class>com.edw.servlet.MainServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>mainServlet</servlet-name>
        <url-pattern>/mainServlet</url-pattern>
    </servlet-mapping>

    <!-- JNDI -->
    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/test</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    
</web-app>

And also, dont forget to put your mysql-connector.jar to tomcat lib. And if you see this error, Cannot create JDBC driver of class '' for connect URL 'null', it means there’s something wrong with your JNDI configuration on context.xml.

This is my netbeans project screenshot

and this is what the result will look like

Have fun, cheers. (B)

Google+

[Tutorial] Upload File atau Image Dengan JSP

Beberapa hari terakhir di forum programmer Kaskus lagi rame pertanyaan tentang caranya upload file pakek JSP. Daripada pusing-pusing mendingan gw pake library bawaan apache, yaitu Apache Commons FileUpload.

Aplikasi sederhana ini terdiri dari 1 buah JSP sebagai presentation layer dan 1 Servlet buat handle uploading file-nya. Konsep-nya sederhana, semua file yang keupload akan disimpan didalam folder /image yang terletak 1 folder dengan file index.jsp.

Oke, langsung kita mulai kalo gitu. Ini file index.jsp gw,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="upload" method="POST" enctype="multipart/form-data">
            Select file : <input type="file" name="fileSelect" />
            <br />
            <input type="submit" />
        </form>
    </body>
</html>

dan ini servlet buat handle upload file ataupun image,

package com.baculsoft.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // get your absolute path
        String uploadTo = getServletContext().getRealPath("/") + "image/";

        try {

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            // no multipart form
            if (!isMultipart) {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet UploadServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>No Multipart Files</h1>");
                out.println("</body>");
                out.println("</html>");
            }
            // multipart form
            else {
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

                // parse requests
                List<FileItem> fileItems = upload.parseRequest(request);

                // Process the uploaded items
                for (FileItem fileItem : fileItems) {
                    // a regular form field
                    if (fileItem.isFormField()) {
                        
                    }
                    // upload field
                    else {
                        String fileName = fileItem.getName();
                        File fileTo = new File(uploadTo + fileName);
                        fileItem.write(fileTo);

                        out.println("<html>");
                        out.println("<head>");
                        out.println("<title>Servlet UploadServlet</title>");
                        out.println("</head>");
                        out.println("<body>");
                        out.println("<h1> success write to " + fileTo.getAbsolutePath() + "</h1>");
                        out.println("</body>");
                        out.println("</html>");

                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

abis itu gw register servlet gw di web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>upload</servlet-name>
        <servlet-class>com.baculsoft.servlet.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>upload</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

ini struktur project gw di Netbeans.

Nah gampang kan ;-)

nb.
untuk tutorial lebih lengkapnya bisa dicek disini

Google+