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

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

Introduction

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

Prototype

public FilePart(String paramString, PartSource paramPartSource) 

Source Link

Usage

From source file:org.wso2.developerstudio.eclipse.carbonserver30.operations.CommonOperations.java

public static String uploadFile(File resourceUrl, String validatorUrl, String url)
        throws HttpException, IOException {
    File f = resourceUrl;//from  w  w w  .j ava 2s .  c om
    PostMethod filePost = new PostMethod(url);
    Part part;
    if (validatorUrl == null)
        part = new FilePart(f.getName(), f);
    else
        part = new FilePart(validatorUrl, f.getName(), f);
    filePost.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, filePost.getParams()));
    HttpClient client = new HttpClient();
    //filePost.setFollowRedirects(true);
    int status = client.executeMethod(filePost);
    String resultUUid = null;
    resultUUid = filePost.getResponseBodyAsString();
    filePost.releaseConnection();
    return resultUUid;
}

From source file:org.wso2.pc.integration.test.utils.base.ArtifactUploadUtil.java

/**
 * This method uploads a BPMN/*from w ww  . j  a  v a 2s  . c o  m*/
 *
 * @param filePath       The absolute path of the file
 * @param processName    Process name
 * @param processVersion Process version
 * @param shortName      Asset shortname mentioned in the RXT
 * @param cookieHeader   Session cookie
 * @throws IOException
 */
public static PostMethod uploadBPMN(String filePath, String processName, String processVersion,
        String shortName, String cookieHeader, String apiUrl) throws IOException {

    File file = new File(filePath);
    FilePart fp = new FilePart(shortName + "_file", file);
    fp.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp1 = new StringPart("bpmnProcessName", processName);
    sp1.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp2 = new StringPart("bpmnProcessVersion", processVersion);
    sp2.setContentType(MediaType.TEXT_PLAIN);
    //Set file parts and string parts together
    final Part[] part = { fp, sp1, sp2 };

    HttpClient httpClient = new HttpClient();
    PostMethod httpMethod = new PostMethod(apiUrl);

    httpMethod.addRequestHeader("Cookie", cookieHeader);
    httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON);
    httpMethod.setRequestEntity(new MultipartRequestEntity(part, httpMethod.getParams()));
    httpClient.executeMethod(httpMethod);
    return httpMethod;
}

From source file:org.wso2.pc.integration.test.utils.base.ArtifactUploadUtil.java

/**
 * This method uploads a document/*from w  w  w .j a  v a2 s.c  o m*/
 *
 * @param filePath       The absolute path of the file
 * @param documentName   document name
 * @param documentSummary summary of the document
 * @param documentExtension extension of the document file
 * @param documentURL    document URL
 * @param processName    Process name
 * @param processVersion Process version
 * @param cookieHeader   Session cookie
 * @throws IOException
 */
public static PostMethod uploadDocument(String filePath, String documentName, String documentSummary,
        String documentExtension, String documentURL, String optionsRadios1, String processName,
        String processVersion, String cookieHeader, String apiUrl, String contentType) throws IOException {

    File file = new File(filePath);
    FilePart fp = new FilePart("PDF" + "_file", file);
    fp.setContentType(contentType);
    StringPart sp1 = new StringPart("docName", documentName);
    sp1.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp2 = new StringPart("summaryDoc", documentSummary);
    sp2.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp3 = new StringPart("docProcessName", processName);
    sp3.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp4 = new StringPart("docProcessVersion", processVersion);
    sp4.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp5 = new StringPart("docExtension", documentExtension);
    sp5.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp6 = new StringPart("docUrl", documentURL);
    sp6.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp7 = new StringPart("optionsRadios1", optionsRadios1);
    sp7.setContentType(MediaType.TEXT_PLAIN);

    //Set file parts and string parts together
    final Part[] part = { fp, sp1, sp2, sp3, sp4, sp5, sp6, sp7 };

    HttpClient httpClient = new HttpClient();
    PostMethod httpMethod = new PostMethod(apiUrl);

    httpMethod.addRequestHeader("Cookie", cookieHeader);
    httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON);
    httpMethod.setRequestEntity(new MultipartRequestEntity(part, httpMethod.getParams()));
    httpClient.executeMethod(httpMethod);
    return httpMethod;
}

From source file:org.wso2.pc.integration.test.utils.base.ArtifactUploadUtil.java

/**
 * This method uploads a process ZIP file
 *
 * @param filePath       The absolute path of the file
 * @param cookieHeader   Session cookie//from  w  ww . ja va 2s. c o m
 * @throws IOException
 */
public static PostMethod uploadProcess(String filePath, String cookieHeader, String apiUrl) throws IOException {

    File file = new File(filePath);
    FilePart fp = new FilePart("processZip", file);

    //Set file parts and string parts together
    final Part[] part = { fp };
    HttpClient httpClient = new HttpClient();
    PostMethod httpMethod = new PostMethod(apiUrl);
    httpMethod.addRequestHeader("Cookie", cookieHeader);
    httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON);
    httpMethod.setRequestEntity(new MultipartRequestEntity(part, httpMethod.getParams()));
    httpClient.executeMethod(httpMethod);
    return httpMethod;
}

From source file:org.wso2.pc.integration.tests.publisher.packages.AddPackageTestCase.java

/**
 * Test case for adding package/*from   w w w  .  ja  va2s.  c  o m*/
 *
 * @throws IOException
 * @throws XPathExpressionException
 * @throws JSONException
 */
@Test(groups = { "org.wso2.pc" }, description = "Test case for adding package")
public void addPackage() throws IOException, XPathExpressionException, JSONException {
    String filePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "BAR"
            + File.separator + "HelloWorld.bar";

    File file = new File(filePath);
    FilePart fp = new FilePart("package_file", file);
    fp.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp1 = new StringPart("package_file_name", "HelloWorld.bar");
    sp1.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp2 = new StringPart("overview_name", "Test Package");
    sp2.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp3 = new StringPart("overview_versionn", "1.0.0");
    sp2.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp4 = new StringPart("overview_description", "This test package");
    sp2.setContentType(MediaType.TEXT_PLAIN);
    //Set file parts and string parts together
    final Part[] part = { fp, sp1, sp2, sp3, sp4 };
    HttpClient httpClient = new HttpClient();
    PostMethod httpMethod = new PostMethod(publisherPackageAPIBaseUrl + "packages?type=package");

    httpMethod.addRequestHeader("Cookie", cookieHeader);
    httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON);
    httpMethod.setRequestEntity(new MultipartRequestEntity(part, httpMethod.getParams()));
    // Add package using package api
    httpClient.executeMethod(httpMethod);
    Assert.assertTrue(httpMethod.getStatusCode() == PCIntegrationConstants.RESPONSE_CODE_CREATED,
            "Expected 201 CREATED, Received " + httpMethod.getStatusCode());
    JSONObject responseObject = new JSONObject(httpMethod.getResponseBodyAsString());
    packageID = responseObject.get(PCIntegrationConstants.ID).toString();
    Assert.assertTrue(responseObject.get("error").toString().equals("false"),
            "Error while creating the package");

}

From source file:org.xwiki.test.rest.AttachmentsResourceTest.java

@Test
public void testPOSTAttachment() throws Exception {
    final String attachmentName = String.format("%s.txt", UUID.randomUUID());
    final String content = "ATTACHMENT CONTENT";

    String attachmentsUri = buildURIForThisPage(AttachmentsResource.class, attachmentName);

    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            TestUtils.ADMIN_CREDENTIALS.getUserName(), TestUtils.ADMIN_CREDENTIALS.getPassword()));
    httpClient.getParams().setAuthenticationPreemptive(true);

    Part[] parts = new Part[1];

    ByteArrayPartSource baps = new ByteArrayPartSource(attachmentName, content.getBytes());
    parts[0] = new FilePart(attachmentName, baps);

    PostMethod postMethod = new PostMethod(attachmentsUri);
    MultipartRequestEntity mpre = new MultipartRequestEntity(parts, postMethod.getParams());
    postMethod.setRequestEntity(mpre);/*w w w  . j  a v  a 2  s.  com*/
    httpClient.executeMethod(postMethod);
    Assert.assertEquals(getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());

    this.unmarshaller.unmarshal(postMethod.getResponseBodyAsStream());

    Header location = postMethod.getResponseHeader("location");

    GetMethod getMethod = executeGet(location.getValue());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    Assert.assertEquals(content, getMethod.getResponseBodyAsString());
}

From source file:org.xwiki.test.storage.framework.StoreTestUtils.java

public static HttpMethod doUpload(final String address, final UsernamePasswordCredentials userNameAndPassword,
        final Map<String, byte[]> uploads) throws IOException {
    final HttpClient client = new HttpClient();
    final PostMethod method = new PostMethod(address);

    if (userNameAndPassword != null) {
        client.getState().setCredentials(AuthScope.ANY, userNameAndPassword);
        client.getParams().setAuthenticationPreemptive(true);
    }/*from   w  w  w. j a va 2 s .c  o  m*/

    Part[] parts = new Part[uploads.size()];
    int i = 0;
    for (Map.Entry<String, byte[]> e : uploads.entrySet()) {
        parts[i++] = new FilePart("filepath", new ByteArrayPartSource(e.getKey(), e.getValue()));
    }
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(entity);

    client.executeMethod(method);
    return method;
}

From source file:oscar.oscarBilling.ca.bc.Teleplan.TeleplanAPI.java

/**
*Procedure parameters: Filename which is a string representing a file on the local system
*Parameters to TeleplanBroker are//from   www.  j a  v  a 2 s . c o m
*ExternalAction = "AputAscii"
*This is a RFC1867 Multi-part post
*Results from TeleplanBroker are:
*                                "SUCCESS" 
*                                "FAILURE"
*/
public TeleplanResponse putAsciiFile(File f) throws FileNotFoundException {

    Part[] parts = { new StringPart("ExternalAction", "AputAscii"), new FilePart("submitASCII", f) };
    return processRequest(CONTACT_URL, parts);

    //    my ($filename) = @_;
    //    my $request = POST $WEBBASE, Content_type => 'form-data',
    //                                 Content      => ['submitASCII'    => [ $filename ], 
    //                                                  'ExternalAction' => 'AputAscii'
    //                                                 ];
    //    my $retVal = processRequest($request);   
    //    if ($retVal == $SUCCESS)
    //    {#valid response
    //       if ($Result ne "SUCCESS")
    //       {
    //           $retVal = $VALID;
    //       }
    //    }
    //    else
    //    {
    //       $retVal = $ERROR;
    //    }
    //    return $retVal;

}

From source file:oscar.oscarBilling.ca.bc.Teleplan.TeleplanAPI.java

/**
*Procedure parameters: Filename which is a string representing a file on the local system
*Parameters to TeleplanBroker are//from w w  w. j  a va2s .  c o m
*ExternalAction = "AputRemit"
*This is a RFC1867 Multi-part post
*Results from TeleplanBroker are:
*                                "SUCCESS"
*                                "FAILURE"
*/
public TeleplanResponse putMSPFile(File f) throws FileNotFoundException {
    Part[] parts = { new StringPart("ExternalAction", "AputRemit"), new FilePart("submitFile", f) };
    return processRequest(CONTACT_URL, parts);
    //
    //    my ($filename) = @_;
    //    my $request = POST $WEBBASE, Content_Type => 'form-data',
    //                                 Content      => ['submitFile'    => [ $filename ], 
    //                                                  'ExternalAction' => 'AputRemit'
    //                                                 ];
    //    my $retVal = processRequest($request);   
    //    if ($retVal == $SUCCESS)
    //    {#valid response
    //       if ($Result ne "SUCCESS")
    //       {
    //           $retVal = $VALID;
    //       }
    //    }
    //    else
    //    {
    //       $retVal = $ERROR;
    //    }
    //    return $retVal;
    //            return null;
}

From source file:pl.nask.hsn2.connector.CuckooRESTConnector.java

public final long sendFile(File file, Set<NameValuePair> cuckooParams)
        throws CuckooException, ResourceException {

    PostMethod post = new PostMethod(cuckooURL + SEND_FILE_TASK);
    try {//  ww  w  . ja  va2 s  .c om
        int size = cuckooParams.size();
        Part[] parts = new Part[size + 1];
        int i = 0;
        for (NameValuePair pair : cuckooParams) {
            parts[i] = new StringPart(pair.getName(), pair.getValue());
            i++;
        }
        parts[i] = new FilePart("file", file);

        RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(entity);
        return sendPost(post);
    } catch (FileNotFoundException e) {
        LOGGER.error("This should never happen!", e);
        throw new ResourceException(e.getMessage(), e);
    }

}