Solved

uploading file in JNLP application

Posted on 2010-11-17
18
1,148 Views
Last Modified: 2013-11-24
The last piece of the puzzle for my application is uploading a file to a web server.  I already have in place the creation of a list of files that are compressed into a single file and this zip file is created on a the local computer.  Now I need to get these files uploaded to the server.  I'll admit that I'm completely clueless  when it comes to client-server development.

I've searched the web to find some examples and have not found much other than I need to have a servlet running.  I've attached some code that was provided to me but I don't believe that is what I need.  I also found links such as http://www.prasannatech.net/2008/11/http-web-server-java-post-file-upload.html which may help me.

But exactly how do I call these servlets from java code?  This is a web start application and does not involve a browser.  As I said earlier, I have compressed the file and have my hands on it, I'm just not sure how to get it to the server or how to hand it off to the servlet.

Thank you for your assistance.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * This is a shell that will handle upload. 
 *
 */
public class Upload extends HttpServlet {

    /**
     * This method writes the most commonly used request information
     * to the response body, such as the User-Agent header, the
     * various paths associated with the request, and the request
     * parameters.
     */
    public void doGet(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

        String name = request.getParameter("name");
        if (name == null) {
            name =  "you";
        }
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Hello " + name + "</h1>");

        out.println("I see that:<ul>");
        String userAgent = request.getHeader("User-Agent");
        out.println("<li>your browser is: " + userAgent);
        String requestURI = request.getRequestURI();
        out.println("<li>the URI for this page is: " +
            requestURI);
        String contextPath = request.getContextPath();
        out.println("<li>the context path for this app is" +
            contextPath);
        String servletPath = request.getServletPath();
        out.println("<li>this servlet is mapped to: " +
            servletPath);
        String pathInfo = request.getPathInfo();
        out.println("<li>the remaining path is: " + pathInfo);
        Map parameters = request.getParameterMap();
        out.println("<li>you sent the following params:<ul>");
        Iterator i = parameters.keySet().iterator();
        while (i.hasNext()) {
            String paramName = (String) i.next();
            out.println("<li><b>" + paramName + "</b>:");
            String[] paramValues =
                (String[]) parameters.get(paramName);
            for (int j = 0; j < paramValues.length; j++) {
                if (j != 0) {
                    out.print(", ");
                }
                out.print(paramValues[j]);
            }
        }
        out.println("</ul></ul></body></html>");
    }
}

Open in new window

0
Comment
Question by:mock5c
  • 8
  • 5
  • 5
18 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
Comment Utility
You need to implement doPost in a servlet and call the servlet from your JWS app using a POST:

http://www.exampledepot.com/egs/java.net/Post.html
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
you can POST it to your servlet, but better offer doing a file upload

you can use commons fileupload to handle the upload in your servlet
http://commons.apache.org/fileupload/

and httpclient or cos to upload the file from your application

let me know if you have any queestions
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
mock5c, you should understand that if you want to make life simpler (simpler even than the method i mentioned originally) you should use a protocol that's designed for transferring files, such as scp, sftp, ftp. File transfer via web pages is a kludgy bolt-on to the http protocol and is neither simple, nor secure (unless done over https)
0
 

Author Comment

by:mock5c
Comment Utility
I am all for making life simpler.  sFTP is an option since it's secure and I have an sftp site available.  Can this be any sftp site or must it be the same as the web server?  This is also JNLP application, in case I have not mentioned that.  Do you have any examples of using sFTP?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
you'll find what i posted above is the simplest

to use ftp you can use something like commons net
http://commons.apache.org/net/
0
 

Author Comment

by:mock5c
Comment Utility
objects, I assume that your suggestion works with the jnlp application.

Perhaps CEHJ and objects should have a battle of the "simplest" and post their code here :)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
the code for all the options I have posted is straightforward and lots of standard solutions exist. more a question of how you want to handle the upload on the server side. Using a servlet would be the most flexible.
So pick how you want to transfer the file then use the appropriate api (see the links I posted above) to implement it.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Although not secure, it can be as simple as this:

http://www.codeguru.com/forum/printthread.php?t=289310
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
you can use the URL class for ftping , but its not the nicest

http://helpdesk.objects.com.au/java/how-to-access-ftp-server-using-url-class
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(Which is what i've just mentioned)
0
 

Author Comment

by:mock5c
Comment Utility
I'm basically scrambling and looking at all of these options.  With apache commons FileUpload, it's not exactly clear where DiskFileItemFactory, ServletFileUpload, etc. are defined since they do not provide complete examples.  I'm assuming this is inside the doPost() servlet method.  Is this correct?
0
 
LVL 92

Assisted Solution

by:objects
objects earned 450 total points
Comment Utility
yes in your doPost and pass the request to ServletFileUpload.parseRequest() for processing


        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Configure the uploader here, if desired.
        List fileItems = upload.parseRequest(request);
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Of all ways to do it, that's the most cumbersome. Bear in mind too that without authentication, *anyone* will be able to upload stuff, with whatever consequences that might entail
0
 

Author Comment

by:mock5c
Comment Utility
I hear you on some methods being more cumbersome than others.  I am trying out a few of these suggestions.  For the commons net method, my sample code is below.  I would appreciate it if anyone could make suggestions on how to work through my problems.  I am getting log information on the server that reports:

From (ServerResponse): java.io.IOException: Server returned HTTP response code: 500 for URL: ...

My objective is simply to send large zip files from the client JNLP/Webstart application to a server where they are stored on disk.  At the moment I am not concerned about processing the file or inserting data into a database.  Eventually I'll probably want to unzip the file but that is not something I'm worried about.  Getting the file uploading working is my priority.

Nathan


//Servlet

   public void doPost(HttpServletRequest req, HttpServletResponse res) {

      System.out.println("... In Upload.doPost() ...");

      try {   
         DiskFileItemFactory factory = new DiskFileItemFactory();
         ServletFileUpload upload = new ServletFileUpload(factory);
         upload.setSizeMax(100000000);

         // maximum size that will be stored in memory
         //factory.setSizeThreshold(1096);
         // the location for saving data that is larger than getSizeThreshold()
         //factory.setRepository(new File("/tmp"));

         List items = upload.parseRequest(req);

         String fileName = "";
         long maxSize = 0;
 
         Iterator iter = items.iterator();
         while (iter.hasNext()) {
            DiskFileItem item = (DiskFileItem) iter.next();

            // filename on the client
            fileName = item.getName();
            maxSize = item.getSize();

            // write the file
            item.write(new File("/tmp", fileName));
          }       
      }
      catch(Exception e) {
         System.out.println("<br>\nError: "+e.getMessage());
      }       
   }

// test app

import java.io.*;
import java.net.*;

public class UploadTest  {
  public static void main(String[] args) throws Exception { 
    HttpURLConnection conn = null; 
    BufferedReader br = null; 
    DataOutputStream dos = null; 
    DataInputStream inStream = null; 

    InputStream is = null; 
    OutputStream os = null; 
    boolean ret = false;
    String StrMessage = "";
    String fileName = "C:\\test.zip";

    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024;
    String responseFromServer = "";
    String urlString = "http://localhost:8080/FileUpload/requestupload";

    try {   
      //------------------ CLIENT REQUEST 
      FileInputStream fileInputStream = new FileInputStream(new File(fileName));

      // open a URL connection to the Servlet 
      URL url = new URL(urlString);
      System.out.println("url = " +url);

      // Open a HTTP connection to the URL 
      conn = (HttpURLConnection) url.openConnection();
      System.out.println("conn = " + conn);

      // Allow Inputs
      conn.setDoInput(true);

      // Allow Outputs 
      conn.setDoOutput(true);

      // Don't use a cached copy.
      conn.setUseCaches(false);

      // Use a post method. 
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

      dos = new DataOutputStream( conn.getOutputStream() );
      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes("Content-Disposition: form-data; name=\"upload\";"
         + " filename=\"" + fileName +"\"" + lineEnd);
      dos.writeBytes(lineEnd);

      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      // send multipart form data necesssary after file data... 

      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

      fileInputStream.close();
      dos.flush();
      dos.close();
    }
    catch (MalformedURLException ex) {
      System.out.println("From ServletCom CLIENT REQUEST:"+ex);
    }

   catch (IOException ioe) {

     System.out.println("From ServletCom CLIENT REQUEST:"+ioe);
   }

   //------------------ read the SERVER RESPONSE

   try {
     inStream = new DataInputStream ( conn.getInputStream() );
     String str;
     while (( str = inStream.readLine()) != null) {
       System.out.println("Server response is: "+str);
       System.out.println("");
     }
     inStream.close();
   }
   catch (IOException ioex) {
     System.out.println("conn = " + conn);
     System.out.println("From (ServerResponse): "+ioex);
   }
 }
}

Open in new window

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
don't reinvent the wheel, use fileupload or cos on the client to handle the upload (theres a link in my earlier comment)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
And theres nothing cumbersome about the approach you are taking. In fact its fairly standard
0
 

Author Comment

by:mock5c
Comment Utility
what do you mean by "cos"?

In the servlet code, which I basically got from commons FileUpload site and am trying to piece together, the line:

List items = upload.parseRequest(req)

seems to be a problem.  I have print statements before and after and the lines after do not print anything.
0
 
LVL 92

Accepted Solution

by:
objects earned 450 total points
Comment Utility
sorry above should have referred you to httpclient for handling the client side
theres an example here
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
how to use external config file with Spring MVC 4 59
countX 22 68
strDist challenge 35 84
Free Alternative to JIRA 4 51
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now