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.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java

/**
 * Used by jsFunction_executeMethod()./*  www.  ja  v  a 2 s. c  om*/
 * 
 * @param httpClient
 * @param contentType
 * @param charset
 * @param methodName
 * @param content
 * @param params
 */
private static void setParams(PooledHttpClientHostObject httpClient, HttpMethod method, String contentType,
        String charset, String methodName, Object content, NativeObject params) {
    // other parameters have been set, they are properly set to the
    // corresponding context
    if (ScriptableObject.getProperty(params, "cookiePolicy") instanceof String) {
        method.getParams().setCookiePolicy((String) ScriptableObject.getProperty(params, "cookiePolicy"));
    } else if (!ScriptableObject.getProperty(params, "cookiePolicy").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "contentType") instanceof String) {
        contentType = (String) ScriptableObject.getProperty(params, "contentType");
    } else if (!ScriptableObject.getProperty(params, "contentType").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "charset") instanceof String) {
        charset = (String) ScriptableObject.getProperty(params, "charset");
    } else if (!ScriptableObject.getProperty(params, "charset").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "timeout") instanceof Integer) {
        method.getParams().setSoTimeout((Integer) ScriptableObject.getProperty(params, "timeout"));
    } else if (!ScriptableObject.getProperty(params, "timeout").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "doAuthentication") instanceof Boolean) {
        method.setDoAuthentication((Boolean) ScriptableObject.getProperty(params, "doAuthentication"));
    } else if (!ScriptableObject.getProperty(params, "doAuthentication").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "followRedirect") instanceof Boolean) {
        method.setFollowRedirects((Boolean) ScriptableObject.getProperty(params, "followRedirect"));
    } else if (!ScriptableObject.getProperty(params, "followRedirect").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (methodName.equals("POST")) {
        // several parameters are specific to POST method
        if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) {
            boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked");
            ((PostMethod) method).setContentChunked(chuncked);
            if (chuncked && content != null) {
                // if contentChucked is set true, then
                // InputStreamRequestEntity or
                // MultipartRequestEntity is used
                if (content instanceof String) {
                    // InputStreamRequestEntity for string content
                    ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity(
                            new ByteArrayInputStream(((String) content).getBytes())));
                } else {
                    // MultipartRequestEntity for Name-Value pair
                    // content
                    NativeObject element;
                    List<StringPart> parts = new ArrayList<StringPart>();
                    String eName;
                    String eValue;
                    // create pairs using name-value pairs
                    for (int i = 0; i < ((NativeArray) content).getLength(); i++) {
                        if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) {
                            element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content);
                            if (ScriptableObject.getProperty(element, "name") instanceof String
                                    && ScriptableObject.getProperty(element, "value") instanceof String) {
                                eName = (String) ScriptableObject.getProperty(element, "name");
                                eValue = (String) ScriptableObject.getProperty(element, "value");
                                parts.add(new StringPart(eName, eValue));
                            } else {
                                throw new RuntimeException("Invalid content definition, objects of the content"
                                        + " array should consists with strings for both key/value");
                            }

                        } else {
                            throw new RuntimeException(
                                    "Invalid content definition, content array should contain "
                                            + "Javascript Objects");
                        }
                    }
                    ((PostMethod) method).setRequestEntity(new MultipartRequestEntity(
                            parts.toArray(new Part[parts.size()]), method.getParams()));
                }
            }

        } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)
                && content != null) {
            // contentChunking has not used
            if (content instanceof String) {
                try {
                    ((PostMethod) method)
                            .setRequestEntity(new StringRequestEntity((String) content, contentType, charset));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("Unsupported Charset");
                }
            } else {
                NativeObject element;
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                String eName;
                String eValue;
                // create pairs using name-value pairs
                for (int i = 0; i < ((NativeArray) content).getLength(); i++) {
                    if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) {
                        element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content);
                        if (ScriptableObject.getProperty(element, "name") instanceof String
                                && ScriptableObject.getProperty(element, "value") instanceof String) {
                            eName = (String) ScriptableObject.getProperty(element, "name");
                            eValue = (String) ScriptableObject.getProperty(element, "value");
                            pairs.add(new NameValuePair(eName, eValue));
                        } else {
                            throw new RuntimeException(
                                    "Invalid content definition, objects of the content array "
                                            + "should consists with strings for both key/value");
                        }

                    } else {
                        throw new RuntimeException("Invalid content definition, content array should contain "
                                + "Javascript Objects");
                    }
                }
                ((PostMethod) method).setRequestBody(pairs.toArray(new NameValuePair[pairs.size()]));
            }
        } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) {
            throw new RuntimeException("Method parameters should be Strings");
        }

    } else if (methodName.equals("GET")) {
        // here, the method now is GET
        if (content != null) {
            if (content instanceof String) {
                method.setQueryString((String) content);
            } else {
                NativeObject element;
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                String eName;
                String eValue;
                // create pairs using name-value pairs
                for (int i = 0; i < ((NativeArray) content).getLength(); i++) {
                    if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) {
                        element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content);
                        if (ScriptableObject.getProperty(element, "name") instanceof String
                                && ScriptableObject.getProperty(element, "value") instanceof String) {
                            eName = (String) ScriptableObject.getProperty(element, "name");
                            eValue = (String) ScriptableObject.getProperty(element, "value");
                            pairs.add(new NameValuePair(eName, eValue));
                        } else {
                            throw new RuntimeException(
                                    "Invalid content definition, objects of the content array "
                                            + "should consists with strings for both key/value");
                        }

                    } else {
                        throw new RuntimeException("Invalid content definition, content array should contain "
                                + "Javascript Objects");
                    }
                }
                method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()]));
            }
        }
    } else if (methodName.equals("PUT")) {
        // several parameters are specific to PUT method
        if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) {
            boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked");
            ((PutMethod) method).setContentChunked(chuncked);
            if (chuncked && content != null) {
                // if contentChucked is set true, then
                // InputStreamRequestEntity or
                // MultipartRequestEntity is used
                if (content instanceof String) {
                    // InputStreamRequestEntity for string content
                    ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity(
                            new ByteArrayInputStream(((String) content).getBytes())));
                } else {
                    throw new RuntimeException(
                            "Invalid content definition, content should be a string when PUT "
                                    + "method is used");
                }
            }

        } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)
                && content != null) {
            // contentChunking has not used
            if (content instanceof String) {
                try {
                    ((PostMethod) method)
                            .setRequestEntity(new StringRequestEntity((String) content, contentType, charset));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("Unsupported Charset");
                }
            } else {
                throw new RuntimeException(
                        "Invalid content definition, content should be a string when PUT " + "method is used");
            }
        } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) {
            throw new RuntimeException("Method parameters should be Strings");
        }

    }

    // check whether preemptive authentication is used
    if (ScriptableObject.getProperty(params, "preemptiveAuth") instanceof Boolean) {
        httpClient.httpClient.getParams()
                .setAuthenticationPreemptive((Boolean) ScriptableObject.getProperty(params, "preemptiveAuth"));
    } else if (!ScriptableObject.getProperty(params, "preemptiveAuth").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }
}

From source file:org.wso2.carbon.registry.es.utils.FileUploadWithAttachmentUtil.java

/**
 * This method uploads a content-type asset (ex: wsdl,policy,wadl,swagger)
 * to a running G-Reg instance/*from w w w  .  j  av a 2s . co m*/
 *
 * @param filePath     The absolute path of the file
 * @param fileVersion  Version of the file
 * @param fileName     Name of the file
 * @param shortName    Asset shortname mentioned in the RXT
 * @param cookieHeader Session cookie
 * @throws IOException
 */
public static PostMethod uploadContentTypeAssets(String filePath, String fileVersion, String fileName,
        String shortName, String cookieHeader, String apiUrl) throws IOException {

    File file = new File(filePath);
    //The api implementation requires fileUpload name in the format
    //of shortname_file (ex: wsdl_file)
    FilePart fp = new FilePart(shortName + "_file", file);
    fp.setContentType(MediaType.TEXT_PLAIN);
    String version = fileVersion;
    String name = fileName;
    StringPart sp1 = new StringPart("file_version", version);
    sp1.setContentType(MediaType.TEXT_PLAIN);
    StringPart sp2 = new StringPart(shortName + "_file_name", name);
    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.developerstudio.eclipse.carbon.server.model.operations.CommonCarbonServerOperations.java

public static String uploadFile(File resourceUrl, String validatorUrl, String url)
        throws HttpException, IOException {
    File f = resourceUrl;/* www.j a v a2  s  .com*/
    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();
    int status = client.executeMethod(filePost);
    String resultUUid = null;
    resultUUid = filePost.getResponseBodyAsString();
    filePost.releaseConnection();
    return resultUUid;
}

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;// w  ww .  j  a v a2 s.  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 w  w. j  a  v  a2  s.co  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  va2  s  .com*/
 *
 * @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  www  .ja  v a  2  s .  c  om*/
 * @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  ww  w . j av  a2 s. 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.xmlblackbox.test.infrastructure.xml.HTTPUploader.java

public void uploadFile(MemoryData memory, HTTPUploader httpClient)
        throws TestException, HttpException, IOException {
    int ris;/*w w w.  jav a 2 s  .  co  m*/
    HttpClient hClient = new HttpClient();

    Properties prop = memory.getOrCreateRepository(getRepositoryName());
    logger.info("prop " + prop);

    /**
     * Effettua la login
     */
    String usernameStr = (String) httpClient.getParameters().get("username");
    String passwordStr = (String) httpClient.getParameters().get("password");

    Properties fileProperties = memory.getOrCreateRepository(Repository.FILE_PROPERTIES);

    logger.info("Login al " + urlLogin);
    PostMethod postMethodLogin = new PostMethod(urlLogin);
    NameValuePair username = new NameValuePair();
    username.setName("userId");
    username.setValue(usernameStr);
    logger.info("username " + usernameStr);
    NameValuePair password = new NameValuePair();
    password.setName("password");
    password.setValue(passwordStr);
    logger.info("password " + passwordStr);

    if (usernameStr != null) {
        postMethodLogin.addParameter(username);
    }
    if (passwordStr != null) {
        postMethodLogin.addParameter(password);
    }
    ris = hClient.executeMethod(postMethodLogin);
    logger.debug("ris Login password " + passwordStr + " " + ris);

    if (ris != HttpStatus.SC_MOVED_TEMPORARILY) {
        throw new TestException("Error during login for uploading the file");
    }

    XmlObject[] domandeXml = null;

    File fileXML = new File(httpClient.getFileToUpload());
    PostMethod postm = new PostMethod(urlUpload);

    logger.debug("fileXML.getName() " + fileXML.getName());
    logger.debug("fileXML " + fileXML);
    logger.debug("postm.getParams()  " + postm.getParams());
    logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_NAME\") "
            + httpClient.getParameters().get("OPERATION_UPLOAD_NAME"));
    logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_VALUE\") "
            + httpClient.getParameters().get("OPERATION_UPLOAD_VALUE"));

    try {
        Part[] parts = {
                new StringPart(httpClient.getParameters().get("OPERATION_UPLOAD_NAME"),
                        httpClient.getParameters().get("OPERATION_UPLOAD_VALUE")),
                new FilePart("file", fileXML.getName(), fileXML) };

        postm.setRequestEntity(new MultipartRequestEntity(parts, postm.getParams()));
        logger.debug("parts " + parts);
    } catch (FileNotFoundException e2) {
        logger.error("FileNotFoundException ", e2);
        throw new TestException(e2, "FileNotFoundException ");
    }

    hClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);

    try {
        ris = hClient.executeMethod(postm);
        logger.info("ris Upload password " + passwordStr + " " + ris);
        logger.debug("ris Upload password " + passwordStr + " " + ris);
        if (ris == HttpStatus.SC_OK) {
            //logger.info("Upload completo, risposta=" + postm.getResponseBodyAsString());

            InputStream in = postm.getResponseBodyAsStream();
            //OutputStream out = new FileOutputStream(new File(prop.getProperty("FILE_RISPOSTA_SERVLET")));
            OutputStream out = new FileOutputStream(new File(httpClient.getFileOutput()));
            OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");

            BufferedReader bufferedReader = new BufferedReader(reader);

            // Transfer bytes from in to out
            //byte[] buf = new byte[1024];
            //int len;
            String linea = null;
            while ((linea = bufferedReader.readLine()) != null) {
                writer.write(linea);
            }
            writer.close();
            reader.close();
            in.close();
            out.close();

        } else {
            logger.error("Upload failed, response =" + HttpStatus.getStatusText(ris));
            logger.error("Exception : Server response not correct ");
            throw new TestException("Exception : Server response not correct ");
        }
    } catch (HttpException e) {
        logger.error("Exception : Server response not correct ", e);
        throw new TestException(e, "");
    } catch (IOException e) {
        logger.error("Exception : Server response not correct ", e);

        throw new TestException(e, "");
    } finally {
        postm.releaseConnection();
    }
}

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);//from  w w w  .ja v  a2s .  c om
    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());
}