Showing posts with label File upload with jersey. Show all posts
Showing posts with label File upload with jersey. 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. 









Sunday, March 2

Jersey web service + File Upload + Maven + Tomcat +Java + Rest Web service









------------------------------------------------------------------------------------------

package com.gs.gsam.lo.du;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

// Plain old Java Object it does not extend as class or implements
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation.
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/upload")
public class DocumentUploader {

    /*
     * // @Produces(MediaType.TEXT_HTML)
     *
     * @GET public String sayHtmlHello() { return " " + " " + "Hello Jerse y  " + "" + "

"
     * + "Hello Jersey" + "

" + " "; }
     */
    @POST
    @Path("/pdf")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("file") File file) {
        InputStream IS = null;;
        String uploadedFileLocation = "d://" + "Test.zip";

        try {
            IS = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }

        // save it
        writeToFile(IS, uploadedFileLocation);

        String output = "The PDF File uploaded to : " + uploadedFileLocation;

        return Response.status(200).entity(output).build();

    }

    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(uploadedFileLocation));
            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();
            uploadedInputStream.close();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();

                }
                if (uploadedInputStream != null) {
                    uploadedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

-------------------------------------------------------------------------

package com.gs.gsam.lo.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

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

import javax.ws.rs.core.MediaType;

public class ClientJ {

  public static void main(String[] args) throws IOException {

      InputStream is=null;
  try {

    Client client = Client.create();

    WebResource webResource = client
       .resource("http://localhost:8080/FileUpload-0.0.1-SNAPSHOT/rest/upload/pdf");

    InputStream IS = null;;

    File file =new File("D:/file/file.zip");
   
    String uploadedFileLocation = "d://" + "Test.zip";

    try {
        IS = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {

    }

    // save it
    writeToFile(IS, uploadedFileLocation);

    String output = "The PDF File uploaded to : " + uploadedFileLocation;
   
    // is=new FileInputStream(file);
   /* ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA)
       .post(ClientResponse.class,file );

    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : "
           + response.getStatus());
    }

    System.out.println("Output from Server .... \n");
    String output = response.getEntity(String.class);
    System.out.println(output);

 */   System.exit(0);
    } catch (Exception e) {

    e.printStackTrace();

    }finally{
        if(null!=is){
            is.close();
        }
    }

  }
 
//save uploaded file to new location
  private static  void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
      OutputStream out = null;
      try {
          out = new FileOutputStream(new File(uploadedFileLocation));
          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();
          uploadedInputStream.close();
      } catch (IOException e) {

          e.printStackTrace();
      } finally {
          try {
              if (out != null) {
                  out.close();

              }
              if (uploadedInputStream != null) {
                  uploadedInputStream.close();
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }

  }

}