UploadDocumentClient.java

From AgileApps Support Wiki
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class UploadDocumentClient {
  
  public static final String REST_SERVICE = 
      "https://{domainName}/networking/RESTService";
  public static final String USER_NAME = "jim@acme.com";
  public static final String PASSWORD = "jimacme";
  
  public static String login() throws Exception
  {
    String sessionId = null;

    StringBuilder loginRequestXML = 
      new StringBuilder("<?xml version=\"1.0\" ?>") 
            .append("    <longjump ver=\"2.0\">")
            .append("      <login_request>")   
            .append("        <login>").append(USER_NAME).append("</login>")   
            .append("        <password>").append(PASSWORD).append("</password>")
            .append("      </login_request>")
            .append("    </longjump>");
    
       // Create an instance of HttpClient.
      HttpClient client = new HttpClient();
      
      //Create GET method
      PostMethod method = new PostMethod(REST_SERVICE);
      
      //add to Request
      method.addParameter("xml_data", loginRequestXML.toString());

       // Provide a custom retry handler (necessary)
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
          new DefaultHttpMethodRetryHandler(3, false));
      try 
      {
          // Execute the method.
          int statusCode = client.executeMethod(method);

          if (statusCode != HttpStatus.SC_OK) 
          {
            System.err.println("Method failed: " + method.getStatusLine());
          }
      
          // Read the response body.
          byte[] responseBody = method.getResponseBody();
          String file = new String(responseBody); 
          int indexOfXMLStart = 
              file.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
          int indexOfXMLEnd = file.indexOf("</longjump>");
                       
          String xmlPartOfResponse = 
            file.substring(indexOfXMLStart, indexOfXMLEnd + 11);
          
          if(xmlPartOfResponse.contains("<session_id>"))
          {
            int sessionIdBeginTagIndx = xmlPartOfResponse.indexOf("<session_id>");
            int sessionIdEndTagIndx = xmlPartOfResponse.indexOf("</session_id>") 
                                    + "</session_id>".length();
            
            sessionId = 
              (xmlPartOfResponse.substring(sessionIdBeginTagIndx, sessionIdEndTagIndx))
                  .replace("<session_id>", "")
                  .replace("</session_id>", "")
                  .trim();
          }
          else if (xmlPartOfResponse.contains("<error>"))
          {
            int messageBeginTagIndx = xmlPartOfResponse.indexOf("<message>");
            int messageEndTagIndx = xmlPartOfResponse.indexOf("</message>")
                                  + "</message>".length();
            
            String message = 
              (xmlPartOfResponse.substring(messageBeginTagIndx, messageEndTagIndx))
                  .replace("<message>", "")
                  .replace("</message>", "")
                  .trim();
            throw new Exception(message);
          }  
      }
      catch (HttpException e) 
      {
          e.printStackTrace(); 
          throw new InvocationTargetException(e, 
              "Fatal protocol violation: " + e.getMessage());
    } 
      catch (IOException e) 
      {
          e.printStackTrace();
          throw new InvocationTargetException(e, 
              "Fatal transport error: " + e.getMessage());
    } 
      catch (Exception e)
      {
        e.printStackTrace();
        throw new InvocationTargetException(e, e.getMessage());
      }
      finally 
      {
          // Release the connection.
          method.releaseConnection();
          return sessionId;
      }
  }
  
  public static void pushDocumentToRemoteServer(
      String userName, String password, 
      String url, String documentFileToUpload)
  {
    String sessionId = null;
    try
    {
      sessionId = login();
    }
    catch(Exception e)
    {
      System.out.println(e.getMessage());
    }
    
    File targetFile = new File(documentFileToUpload);    
    StringBuilder uploadPackageXML = 
      new StringBuilder("<?xml version=\"1.0\" ?>") 
            .append("  <longjump ver=\"2.0\">")
            .append("    <resource_upload_request>")
            .append("      <session_id>")
            .append(sessionId).append("</session_id>")
            .append("        <type>DOCUMENTS</type>")
            .append(" <title>Document Uploaded with out Reference</title>")
            .append("<description>Document upload with our reference</description>")
            .append("<private></private>")
            .append("<folder_id>bd71b54708394b788f759608e38f68e8</folder_id>")
            .append("<flag_public_document>1</flag_public_document>")
            .append("    </resource_upload_request>")
            .append("  </longjump>");
    
    // Create an instance of HttpClient.
      HttpClient client = new HttpClient();
      
      //Create GET method
      PostMethod method = new PostMethod(url);
      FilePart fp = null;
      StringPart sp = null;
      try 
      {
        fp = new FilePart(targetFile.getName(), targetFile);
      } 
      catch (FileNotFoundException e1) 
      {
        // TODO Auto-generated catch block
        System.out.println(e1.getMessage());
      } 
      sp= new StringPart("xml_data", uploadPackageXML.toString());
                
      //add to Request
      Part[] parts = {fp,sp};
      
    method.setRequestEntity(
      (RequestEntity)new MultipartRequestEntity(parts,method.getParams()));
      
      // Provide custom retry handler (necessary)
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
          new DefaultHttpMethodRetryHandler(3, false));
      try 
      {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) 
        {
          throw new Exception("Method failed: " + method.getStatusLine());
        }
    
        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        String file = new String(responseBody);   
        int indexOfXMLStart = 
            file.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        int indexOfXMLEnd = file.indexOf("</longjump>");
        String xmlPartOfResponse = file.substring(indexOfXMLStart, 
                                                  indexOfXMLEnd + 11);
        
        int messageBeginTagIndx = xmlPartOfResponse.indexOf("<message>");        
        int messageEndTagIndx = xmlPartOfResponse.indexOf("</message>") 
                              + "</message>".length();
        
        String message = 
          (xmlPartOfResponse.substring(messageBeginTagIndx, messageEndTagIndx))
              .replace("<message>", "").replace("</message>", "").trim();
        if(xmlPartOfResponse.contains("<success>"))
        {
          System.out.println(message);
        }
        else
        {
          throw new Exception(message);
        }
      }
      catch (HttpException e) 
      {
        System.out.println(e.getMessage());
      } 
      catch (IOException e) 
      {
        System.out.println(e.getMessage());
      } 
      catch (Exception e)
      {
        System.out.println(e.getMessage());
      }
      finally 
      {
        // Release the connection.
        method.releaseConnection();
      }
  }
  
public static void main(String args[])
  {
    UploadDocumentClient upc = new UploadDocumentClient();
    String documentLocation ="C:\\myDocument.doc";
    try
    {
      upc.pushDocumentToRemoteServer(USER_NAME, PASSWORD,
                                     REST_SERVICE, documentLocation);
    }
    catch(Exception e)
    {
      System.out.println(e.getMessage());
    }
  }
}