Example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity.

Prototype

public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams) 

Source Link

Usage

From source file:modnlp.capte.AlignerUtils.java

@SuppressWarnings("deprecation")
/* This method creates the HTTP connection to the server 
 * and sends the POST request with the two files for alignment,
 * /* w w  w  . j a v a2s  .c  o  m*/
 * The server returns the aligned file as the response to the post request, 
 * which is delimited by the tag <beginalignment> which separates the file
 * from the rest of the POST request
 * 
 * 
 * 
 */
public static String MultiPartFileUpload(String source, String target) throws IOException {
    String response = "";
    String serverline = System.getProperty("capte.align.server"); //"http://ronaldo.cs.tcd.ie:80/~gplynch/aling.cgi";   
    PostMethod filePost = new PostMethod(serverline);
    // Send any XML file as the body of the POST request
    File f1 = new File(source);
    File f2 = new File(target);
    System.out.println(f1.getName());
    System.out.println(f2.getName());
    System.out.println("File1 Length = " + f1.length());
    System.out.println("File2 Length = " + f2.length());
    Part[] parts = {

            new StringPart("param_name", "value"), new FilePart(f2.getName(), f2),
            new FilePart(f1.getName(), f1) };
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(filePost);
    String res = "";
    InputStream is = filePost.getResponseBodyAsStream();
    Header[] heads = filePost.getResponseHeaders();
    Header[] feet = filePost.getResponseFooters();
    BufferedInputStream bis = new BufferedInputStream(is);

    String datastr = null;
    StringBuffer sb = new StringBuffer();
    byte[] bytes = new byte[8192]; // reading as chunk of 8192
    int count = bis.read(bytes);
    while (count != -1 && count <= 8192) {
        datastr = new String(bytes, "UTF8");

        sb.append(datastr);
        count = bis.read(bytes);
    }

    bis.close();
    res = sb.toString();

    System.out.println("----------------------------------------");
    System.out.println("Status is:" + status);
    //System.out.println(res);
    /* for debugging
    for(int i = 0 ;i < heads.length ;i++){
      System.out.println(heads[i].toString());
                   
    }
    for(int j = 0 ;j < feet.length ;j++){
      System.out.println(feet[j].toString());
                   
    }
    */
    filePost.releaseConnection();
    String[] handle = res.split("<beginalignment>");
    //Check for errors in the header
    // System.out.println(handle[0]);
    //Return the required text
    String ho = "";
    if (handle.length < 2) {
        System.out.println("Server error during alignment, check file encodings");
        ho = "error";
    } else {
        ho = handle[1];
    }
    return ho;

}

From source file:com.epam.wilma.service.http.WilmaHttpClient.java

/**
 * Posting the given file to the given URL via HTTP POST method and returns
 * {@code true} if the request was successful.
 *
 * @param url the given URL/*from w  w  w.  j  ava 2  s .  c  om*/
 * @param file the given file
 * @return {@code true} if the request is successful, otherwise return {@code false}
 */
public boolean uploadFile(String url, File file) {
    boolean requestSuccessful = false;

    PostMethod method = new PostMethod(url);

    try {
        Part[] parts = { new FilePart("file", file) };
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        int statusCode = httpclient.executeMethod(method);
        if (HttpStatus.SC_OK == statusCode) {
            requestSuccessful = true;
        }
    } catch (HttpException e) {
        LOG.error("Protocol exception occurred when called: " + url, e);
    } catch (IOException e) {
        LOG.error("I/O (transport) error occurred when called: " + url, e);
    } finally {
        method.releaseConnection();
    }

    return requestSuccessful;
}

From source file:com._17od.upm.transport.HTTPTransport.java

public void put(String targetLocation, File file, String username, String password) throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "upload.php";

    PostMethod post = new PostMethod(targetLocation);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {/*from w  w w .j a  v a 2s. co  m*/

        Part[] parts = { new FilePart("userfile", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        //Set the HTTP authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL url = new URL(targetLocation);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        // This line makes the HTTP call
        int status = client.executeMethod(post);

        // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt
        // The second attempt works so lets just do that
        if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
            status = client.executeMethod(post);
        }

        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (FileNotFoundException e) {
        throw new TransportException(e);
    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {/*from w w  w.  j av a 2 s  . c o  m*/
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.sun.faban.harness.util.DeployTask.java

/**
 * Executes the Faban deployment task.//from   ww w. j av a  2  s .  co  m
 * @throws BuildException If there is an
 */
public void execute() throws BuildException {
    try {
        // First check the jar file and name
        if (jarFile == null)
            throw new BuildException("jar attribute missing for target deploy.");
        if (!jarFile.isFile())
            throw new BuildException("jar file not found.");
        String jarName = jarFile.getName();
        if (!jarName.endsWith(".jar"))
            throw new BuildException("Jar file name must end with \".jar\"");
        jarName = jarName.substring(0, jarName.length() - 4);
        if (jarName.indexOf('.') > -1)
            throw new BuildException("Jar file name must not have any " + "dots except ending with \".jar\"");

        // Prepare the parts for the request.
        ArrayList<Part> params = new ArrayList<Part>(4);
        if (user != null)
            params.add(new StringPart("user", user));
        if (password != null)
            params.add(new StringPart("password", password));
        if (clearConfig)
            params.add(new StringPart("clearconfig", "true"));
        params.add(new FilePart("jarfile", jarFile));
        Part[] parts = new Part[params.size()];
        parts = params.toArray(parts);

        // Prepare the post method.
        PostMethod post = new PostMethod(target + "/deploy");

        // Ensure text/plain is the only accept header.
        post.removeRequestHeader("Accept");
        post.setRequestHeader("Accept", "text/plain");
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // Execute the multi-part post method.
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);
        StringBuilder b = new StringBuilder();
        InputStream respBody = post.getResponseBodyAsStream();
        byte[] readBuffer = new byte[8192];
        for (;;) {
            int size = respBody.read(readBuffer);
            if (size == -1)
                break;
            b.append(new String(readBuffer, 0, size));
        }
        String response = b.toString();

        // Check status.
        if (status == HttpStatus.SC_CONFLICT) {
            handleErrorFlush(response);
            throw new BuildException(
                    "Benchmark to deploy is currently " + "run or queued to be run. Please clear run queue "
                            + "of this benchmark before deployment");
        } else if (status == HttpStatus.SC_NOT_ACCEPTABLE) {
            handleErrorFlush(response);
            throw new BuildException(
                    "Benchmark deploy name or deploy " + "file invalid. Deploy file may contain errors. Name "
                            + "must have no '.' and file must have the " + "'.jar' extensions.");
        } else if (status != HttpStatus.SC_CREATED) {
            handleOutput(response);
            throw new BuildException(
                    "Faban responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        }
    } catch (FileNotFoundException e) {
        throw new BuildException(e);
    } catch (HttpException e) {
        throw new BuildException(e);
    } catch (IOException e) {
        throw new BuildException(e);
    }
}

From source file:net.morphbank.webclient.ProcessFiles.java

public InputStream post(String strURL, String strXMLFilename, PrintWriter out) throws Exception {
    InputStream response = null;//  ww w  .  j a  v  a2 s.c o m
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream Part[] parts = {
    Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    // RequestEntity entity = new FileRequestEntity(input,
    // "text/xml;charset=utf-8");
    post.setRequestEntity(entity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        response = post.getResponseBodyAsStream();
        for (int i = response.read(); i != -1; i = response.read()) {
            out.write(i);
        }
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    return response;
}

From source file:com.apatar.ui.JHelpDialog.java

private void addListeners() {
    sendButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            PostMethod filePost = new PostMethod(getUrl());

            // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            try {
                List<File> targetFiles = getAttachFiles();
                Part[] parts;//from   w w  w  .j a v a2 s  .c  o  m
                if (targetFiles != null) {
                    parts = new Part[targetFiles.size() + 1];
                    int i = 1;
                    for (File targetFile : targetFiles) {
                        parts[i++] = new FilePart("file" + i, targetFile);
                    }
                    ;
                } else
                    parts = new Part[1];

                parts[0] = new StringPart("FeatureRequest", text.getText());

                filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(filePost);
                if (status != HttpStatus.SC_OK) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                            "Upload failed, response=" + HttpStatus.getStatusText(status));
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

        }

    });
}

From source file:fedora.test.integration.TestLargeDatastreams.java

private String upload() throws Exception {
    String url = fedoraClient.getUploadURL();
    EntityEnclosingMethod httpMethod = new PostMethod(url);
    httpMethod.setDoAuthentication(true);
    httpMethod.getParams().setParameter("Connection", "Keep-Alive");
    httpMethod.setContentChunked(true);/*from   w ww  .j a  va2  s  .c o  m*/
    Part[] parts = { new FilePart("file", new SizedPartSource()) };
    httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
    HttpClient client = fedoraClient.getHttpClient();
    try {

        int status = client.executeMethod(httpMethod);
        String response = new String(httpMethod.getResponseBody());

        if (status != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(status) + ": "
                    + replaceNewlines(response, " "));
        } else {
            response = response.replaceAll("\r", "").replaceAll("\n", "");
            return response;
        }
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:ccc.migration.FileUploader.java

private ResourceSummary uploadFile(final String hostPath, final UUID parentId, final String fileName,
        final String originalTitle, final String originalDescription, final Date originalLastUpdate,
        final PartSource ps, final String contentType, final String charset, final boolean publish)
        throws IOException {

    final PostMethod filePost = new PostMethod(hostPath);

    try {//  www.java2  s  .com
        LOG.debug("Migrating file: " + fileName);
        final String name = ResourceName.escape(fileName).toString();

        final String title = (null != originalTitle) ? originalTitle : fileName;

        final String description = (null != originalDescription) ? originalDescription : "";

        final String lastUpdate;
        if (originalLastUpdate == null) {
            lastUpdate = "" + new Date().getTime();
        } else {
            lastUpdate = "" + originalLastUpdate.getTime();
        }

        final FilePart fp = new FilePart("file", ps);
        fp.setContentType(contentType);
        fp.setCharSet(charset);
        final Part[] parts = { new StringPart("fileName", name), new StringPart("title", title),
                new StringPart("description", description), new StringPart("lastUpdate", lastUpdate),
                new StringPart("path", parentId.toString()), new StringPart("publish", String.valueOf(publish)),
                fp };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        _client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);

        final int status = _client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            final String entity = filePost.getResponseBodyAsString();
            LOG.debug("Upload complete, response=" + entity);

            return new S11nProvider<ResourceSummary>().readFrom(ResourceSummary.class, ResourceSummary.class,
                    null, MediaType.valueOf(filePost.getResponseHeader("Content-Type").getValue()), null,
                    filePost.getResponseBodyAsStream());
        }

        throw RestExceptionMapper.fromResponse(filePost.getResponseBodyAsString());

    } finally {
        filePost.releaseConnection();
    }
}

From source file:ch.sportchef.business.event.bundary.EventImageResourceTest.java

@Test
public void uploadImageWithOK() throws IOException, ServletException {
    // arrange/*from ww w. ja va  2  s.  c om*/
    final byte[] fileContent = readTestImage();
    final Part[] parts = new Part[] {
            new FilePart(TEST_IMAGE_NAME, new ByteArrayPartSource(TEST_IMAGE_NAME, fileContent)) };
    final MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());
    final ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(requestContent);
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(requestContent.toByteArray());
    final ServletInputStreamMock inputStreamMock = new ServletInputStreamMock(inputStream);
    final String contentType = multipartRequestEntity.getContentType();

    expect(httpServletRequest.getContentType()).andStubReturn(contentType);
    expect(httpServletRequest.getInputStream()).andStubReturn(inputStreamMock);

    eventImageServiceMock.uploadImage(anyLong(), anyObject());
    mockProvider.replayAll();

    // act
    final Response response = eventImageResource.uploadImage(httpServletRequest);

    // assert
    assertThat(response.getStatus(), is(OK.getStatusCode()));
    mockProvider.verifyAll();
}