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:org.seasar.cubby.controller.impl.MultipartRequestParserImplMultipartRequestTest.java

@Test
public void getParameterMapEmpty() throws Exception {
    final PostMethod method = new PostMethod();
    final Part[] parts = new Part[0];
    this.entity = new MultipartRequestEntity(parts, method.getParams());
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    this.entity.writeRequest(out);
    out.flush();/*  w  w w . j a v a  2s  . c  om*/
    out.close();
    this.input = new ByteArrayInputStream(out.toByteArray());

    final Map<String, Object[]> parameterMap = requestParser.getParameterMap(request);
    assertTrue("parameterMap.isEmpty()", parameterMap.isEmpty());
}

From source file:org.soaplab.gowlab.GowlabJob.java

/**************************************************************************
 * Fill 'httpMethod' with the user data (from 'formData',
 * 'queryString' and 'fileData') and execute it. It will do the
 * real data fetching.//from   ww w  . j  a v  a  2  s.com
 *
 * If the fetching finished successfully the 'httpMethod' has the
 * response.
 *************************************************************************/
protected void getResponse() throws SoaplabException {

    if (isGetUsed()) {

        // GET method...

        if (StringUtils.isNotEmpty(queryString)) {
            // ...from a query string
            try {
                httpMethod.setQueryString(URIUtil.encodeQuery(queryString));
            } catch (URIException e) {
                httpMethod.setQueryString(queryString);
            }

        } else {
            // ...from name-value pairs
            httpMethod.setQueryString(formData);
        }

    } else if (isPostUsed()) {

        // POST method...

        // ...from name-value pairs
        ((PostMethod) httpMethod).setRequestBody(formData);

        // ...files to be uploaded
        if (isMultipartUsed()) {
            httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            List<Part> parts = new ArrayList<Part>();
            for (IOData io : fileData) {
                if (!io.getDefinition().isRegularInput())
                    continue;
                File forUpload = io.getData();
                if (forUpload == null)
                    continue;
                try {
                    String tag = io.getDefinition().get(ParamDef.TAG);
                    if (StringUtils.isEmpty(tag))
                        tag = io.getDefinition().id;
                    parts.add(new FilePart(tag, forUpload));
                } catch (FileNotFoundException e) {
                    internalError("A file for uploading was not found: " + forUpload.getAbsolutePath());
                }
            }
            ((PostMethod) httpMethod).setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[] {}), httpMethod.getParams()));
        }
    }

    // finally, execute the method
    try {
        // instantiating an HttpClient
        new HttpClient().executeMethod(httpMethod);

    } catch (HttpException e) {
        internalError("Fatal protocol violation: " + e.getMessage());
    } catch (IOException e) {
        logAndThrow("Fatal transport error: " + e.getMessage());
    }

}

From source file:org.soitoolkit.commons.mule.mime.MimeUtil.java

public static String sendFileAsMultipartHttpPost(String targetURL, File targetFile, String partName,
        boolean expectHeader, int timeoutMs) {

    logger.debug("Send file {} to url {}", targetFile.getAbsolutePath(), targetURL);

    String response = null;/*from w  w  w  .  j av  a  2  s  .  c o  m*/

    PostMethod filePost = new PostMethod(targetURL);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, expectHeader);

    try {

        Part[] parts = { new FilePart(partName, targetFile) };

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeoutMs);

        int status = client.executeMethod(filePost);

        logger.debug("Send done, http status: {}", status);

        if (status == HttpStatus.SC_OK) {
            response = filePost.getResponseBodyAsString();
            logger.debug("Send done, http response: {}", response);
        } else {
            String errorText = HttpStatus.getStatusText(status);
            throw new RuntimeException("HTTP Error Code: " + status + "HTTP Error Text: " + errorText);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }

    return response;
}

From source file:org.sonar.report.pdf.util.FileUploader.java

public static void upload(final File file, final String url, String username, String password) {
    PostMethod filePost = new PostMethod(url);

    try {/*w ww  .  java 2 s  . c  o m*/
        LOG.info("Uploading PDF to server...");

        Part[] parts = { new FilePart("upload", file) };

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
            client.getParams().setAuthenticationPreemptive(true);
            Credentials credentials = new UsernamePasswordCredentials(username, password);
            client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    credentials);
        }
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            LOG.info("PDF uploaded.");
        } else {
            LOG.error("Something went wrong storing the PDF at server side. Status: " + status);
        }
    } catch (Exception ex) {
        LOG.error("Something went wrong storing the PDF at server side", ex);
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.sonatype.nexus.test.utils.DeployUtils.java

public int deployUsingGavWithRest(final String restServiceURL, final String repositoryId, final Gav gav,
        final File fileToDeploy) throws IOException {
    // the method we are calling
    final PostMethod filePost = new PostMethod(restServiceURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    final String extension = gav.getExtension() != null ? gav.getExtension() : "";
    final String classifier = gav.getClassifier() != null ? gav.getClassifier() : "";

    final Part[] parts = { new StringPart("r", repositoryId), new StringPart("g", gav.getGroupId()),
            new StringPart("a", gav.getArtifactId()), new StringPart("v", gav.getVersion()),
            new StringPart("p", extension), new StringPart("c", classifier),
            new FilePart(fileToDeploy.getName(), fileToDeploy) };

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    return nexusRestClient.executeHTTPClientMethod(filePost).getStatusCode();

}

From source file:org.sonatype.nexus.test.utils.DeployUtils.java

public HttpMethod deployUsingPomWithRestReturnResult(final String restServiceURL, final String repositoryId,
        final File fileToDeploy, final File pomFile, final String classifier, final String extension)
        throws IOException {
    // the method we are calling
    final PostMethod filePost = new PostMethod(restServiceURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    final String fixedClassifier = (classifier == null) ? "" : classifier;
    final String fixedExtension = (extension == null) ? "" : extension;

    final Part[] parts = { new StringPart("r", repositoryId), new StringPart("e", fixedExtension),
            new StringPart("c", fixedClassifier), new StringPart("hasPom", "true"),
            new FilePart(pomFile.getName(), pomFile), new FilePart(fileToDeploy.getName(), fileToDeploy) };

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    LOG.debug("URL:  " + restServiceURL);
    LOG.debug("Method: Post");
    LOG.debug("params: ");
    LOG.debug("\tr: " + repositoryId);
    LOG.debug("\thasPom: true");
    LOG.debug("\tpom: " + pomFile);
    LOG.debug("\tfileToDeploy: " + fileToDeploy);

    return nexusRestClient.executeHTTPClientMethod(filePost);
}

From source file:org.sonatype.nexus.test.utils.DeployUtils.java

public HttpMethod deployPomWithRest(final String repositoryId, final File pomFile) throws IOException {
    // the method we are calling
    final PostMethod filePost = new PostMethod(
            nexusRestClient.toNexusURL("service/local/artifact/maven/content").toExternalForm());
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    final Part[] parts = { new StringPart("r", repositoryId), new StringPart("hasPom", "true"),
            new FilePart(pomFile.getName(), pomFile) };

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    LOG.debug("URL:  " + filePost.getURI());
    LOG.debug("Method: Post");
    LOG.debug("params: ");
    LOG.debug("\tr: " + repositoryId);
    LOG.debug("\thasPom: true");
    LOG.debug("\tpom: " + pomFile);

    return nexusRestClient.executeHTTPClientMethod(filePost);
}

From source file:org.sonatype.nexus.test.utils.DeployUtils.java

public int deployWithRest(final String restServiceURL, final String repositoryId, final String groupId,
        final String artifactId, final String version, final String classifier, final String extension,
        final File fileToDeploy) throws IOException {
    // the method we are calling
    final PostMethod filePost = new PostMethod(restServiceURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    final Part[] parts = { new StringPart("r", repositoryId), new StringPart("g", groupId),
            new StringPart("a", artifactId), new StringPart("v", version),
            new StringPart("p", extension == null ? "" : extension),
            new StringPart("c", classifier == null ? "" : classifier),
            new FilePart(fileToDeploy.getName(), fileToDeploy) };

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    return nexusRestClient.executeHTTPClientMethod(filePost).getStatusCode();

}

From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java

public void uploadAttachment(int ticketId, String fileName, String comment, String description,
        AbstractTaskAttachmentSource source, IProgressMonitor monitor) throws RedmineException {
    PostMethod method = new PostMethod(REDMINE_URL_TICKET_EDIT + ticketId);

    //assigned by RedmineAuthenticityTokenAspect
    NameValuePair tokenValue = method.getParameter(CLIENT_FIELD_CSRF_TOKEN);

    List<Part> parts = new ArrayList<Part>(4);
    parts.add(new StringPart(CLIENT_FIELD_ATTACHMENT_DESCRIPTION, description, characterEncoding));
    parts.add(new StringPart(CLIENT_FIELD_ATTACHMENT_NOTES, comment, characterEncoding));
    if (tokenValue != null) {
        parts.add(new StringPart(CLIENT_FIELD_CSRF_TOKEN, tokenValue == null ? "" : tokenValue.getValue(), //$NON-NLS-1$
                characterEncoding));/* w  w w  . j a va  2  s .c om*/
    }

    //Workaround: http://rack.lighthouseapp.com/projects/22435/tickets/79-multipart-handling-incorrectly-assuming-file-upload
    for (Part part : parts) {
        ((StringPart) part).setContentType(null);
    }

    parts.add(new FilePart(CLIENT_FIELD_ATTACHMENT_FILE, new TaskAttachmentPartSource(source, fileName),
            source.getContentType(), this.httpClient.getParams().getContentCharset()));
    method.setRequestEntity(
            new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams()));

    String errorMsg = executeMethod(method, submitErrorParser, monitor, HttpStatus.SC_OK,
            HttpStatus.SC_MOVED_TEMPORARILY);
    if (errorMsg != null) {
        throw new RedmineStatusException(IStatus.INFO, errorMsg);
    }
}

From source file:org.tranche.server.logs.LogUtil.java

/**
 * Upload a log file to server./*from   w w  w.ja va 2  s  .  c o  m*/
 * @param isCompleteHour True only if an entire hour has passed.
 * @return True if server returns HTTP code stating already added, false otherwise.
 */
public static boolean uploadLogFile(File logFile, String fromServerIP, String POST_URL, boolean isCompleteHour)
        throws Exception {

    boolean isAlreadyAdded = false;

    // If url doesn't start with http, see if it is local dir.
    if (!POST_URL.startsWith("http:")) {
        File localDir = new File(POST_URL);

        if (localDir.exists() && localDir.isDirectory()) {
            File copy = new File(localDir, logFile.getName());
            copy.createNewFile();
            IOUtil.copyFile(logFile, copy);

            printTracer("Log copied to " + copy.getAbsolutePath());
            // Doesn't matter, test
            return true;
        }
    }

    int tryCount = 0;
    boolean tryAgain = true;

    while (tryAgain) {
        try {

            // Multipart POST
            PostMethod filePost = new PostMethod(POST_URL);

            FilePart filePart = new FilePart("log", logFile);

            Part[] parts = { new StringPart("server", fromServerIP),
                    new StringPart("isCompleteHour", String.valueOf(isCompleteHour)), filePart };

            printTracer("Uploading log (server=" + fromServerIP + ",isCompleteHour=" + isCompleteHour + ") at "
                    + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp()));

            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
            HttpClient client = new HttpClient();
            int status = client.executeMethod(filePost);

            // Status code of 200 means that the server log was already processed. 
            // 202 means successfully queued.

            if (status == 200) {
                isAlreadyAdded = true;
            }

            if (status < 400) {
                tryAgain = false;
            }
            if (status >= 400) {
                throw new UploadFailedException("Couldn't post log to server, HTTP response code: " + status);
            }

        } catch (UploadFailedException lfx) {
            // rethrow
            throw lfx;
        } catch (Exception ex) {
            tryCount++;
            if (tryCount > 3) {
                // Give up
                tryAgain = false;
            }
        }
    } // while try again...

    return isAlreadyAdded;
}