Showing posts with label jersey rest service. Show all posts
Showing posts with label jersey rest service. Show all posts

Monday, March 17

File upload Jersey Grizzly example




1. Below class is required to startup the grizzly embedded container

package com.example;

import org.glassfish.grizzly.http.server.HttpServer;
importorg.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.io.IOException;
import java.net.URI;

/**
 * Main class.
 *
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8080/myapp/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.example package
        final ResourceConfig rc = new ResourceConfig().packages("com.example");

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
        System.in.read();
        server.stop();
    }
}


As highlighted in above code this Main class will register all the web service classes lying under com.example package . SO Let us create our upload service in example package 


 import com.sun.jersey.multipart.FormDataParam;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
    
    @Path("/files")
    public class JerseyFileUpload {
    
        @POST
        @Path("/upload/{filename}")
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        @Produces(MediaType.TEXT_PLAIN)
        public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream ,@PathParam("filename") String fileName)
{
    
            System.out.println("fileName"+fileName);
           // String uploadedFileLocation = "c://uploadedFiles/" + "fileDetail.getFileName()";
            String uploadedFileLocation = "D:/desktops/12march2014/uploads/"+fileName;
            // save it
            saveToFile(uploadedInputStream, uploadedFileLocation);
    
            String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
    
            return Response.status(200).entity(output).build();
    
        }
    
        // save uploaded file to new location
        private void saveToFile(InputStream uploadedInputStream,
            String uploadedFileLocation) {

    
            try {
                OutputStream out = null;
                int read = 0;
                byte[] bytes = new byte[1024];
    
                out = new FileOutputStream(new File(uploadedFileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();
            } catch (IOException e) {
    
                e.printStackTrace();
            }
    
        }
    
    }


That was server side Code. Execute the Main.java class as java application. It will start up the Grizzly server and JerseyUpload service will be up and running.


-->



Now Lets write Client Code to call this service :

package com.sapient;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class JerseyClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        File file = new File("C:/Users/mkum63/Downloads/spring-framework-2.5-with-dependencies.zip");

        if (args.length >0 && null != args[0]) {
            file = new File(args[0]);
        } else {
           
            System.out.println("Enter full path of file..");

            String path;

            Scanner scanIn = new Scanner(System.in);
            path = scanIn.nextLine();

            file = new File(path);

        }
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost =
                new HttpPost("http://localhost:8080/myapp/files/upload/" + file.getName());
        FileBody fileContent = new FileBody(file);
        try {
            StringBody comment = new StringBody("Filename: " + file.getName());
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", fileContent);
        httppost.setEntity(reqEntity);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
            System.out.println(response.getStatusLine().getStatusCode() == 200 ? "successful" : "Failed");
            // System.out.println(response.getStatusLine().getStatusCode());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpEntity resEntity = response.getEntity();

    }

}


This is the client .Execute this class as java application and supply the full path of the file to be uploaded. 

You can keep your server files and client files on different machines.