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: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 {/*from   w  ww .  j a v a 2 s  .  c  o m*/
        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: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;/*  www .j a  v a  2  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: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/*w w  w.jav  a 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   ww w  . j a v a2s.  com

        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: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 w w .j a v  a 2 s.  co 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:ch.sportchef.business.event.bundary.EventImageResourceTest.java

@Test
public void uploadImageWithOK() throws IOException, ServletException {
    // arrange//from   w  w  w  .  ja v a  2  s .c o  m
    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();
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testAdminUploadWithCsrfInHeader() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(
            LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);//from w  w  w  .  j  a  v  a  2s .c o m
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost",
            ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken);
    int statusCode = HttpClientUtil.executeMethod(client, post);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:com.zb.app.external.wechat.service.WeixinService.java

public void upload(File file, String type) {
    StringBuilder sb = new StringBuilder(400);
    sb.append("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=");
    sb.append(getAccessToken());//from www .ja v a2 s.c  o  m
    sb.append("&type=").append(type);

    PostMethod postMethod = new PostMethod(sb.toString());
    try {
        // FilePart?
        FilePart fp = new FilePart("filedata", file);
        Part[] parts = { fp };
        // MIMEhttpclientMulitPartRequestEntity
        MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
        postMethod.setRequestEntity(mre);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.error(postMethod.getResponseBodyAsString());
        } else {
            logger.error("fail");
        }
        byte[] responseBody = postMethod.getResponseBody();
        String result = new String(responseBody, "utf-8");
        logger.error("result : " + result);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        postMethod.releaseConnection();
    }
}

From source file:com.bakhtiyor.android.tumblr.TumblrService.java

private void uploadPhoto(String email, String password, String caption, boolean isPrivate, String filename) {
    try {//from   ww w .  j a  v a2s  .co  m
        File file = new File(filename);
        final HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        final PostMethod multipartPost = new PostMethod(API_URL);
        Part[] parts = { new StringPart(FIELD_EMAIL, email), new StringPart(FIELD_PASSWORD, password),
                new StringPart(FIELD_TYPE, "photo"), new StringPart("generator", GENERATOR),
                new StringPart(FIELD_CAPTION, caption), new StringPart(FIELD_PRIVATE, isPrivate ? "1" : "0"),
                new FilePart("data", file) };
        multipartPost.setRequestEntity(new MultipartRequestEntity(parts, multipartPost.getParams()));
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        int id = new Random().nextInt();
        showUploadingNotification(id);
        int status = httpClient.executeMethod(multipartPost);
        clearNotification(id);
        if (status == 201) {
            showResultNotification("Successful Uploaded");
        } else {
            showResultNotification("Error occured");
        }
    } catch (Throwable e) {
        Log.e(TAG, e.getMessage(), e);
    }
}

From source file:com.intuit.tank.http.multipart.MultiPartRequest.java

protected List<Part> buildParts() {
    List<Part> parts = new ArrayList<Part>();
    for (PartHolder h : parameters) {
        if (h.getFileName() == null) {
            StringPart stringPart = new StringPart(h.getPartName(), new String(h.getBodyAsString()));
            if (h.isContentTypeSet()) {
                stringPart.setContentType(h.getContentType());
            }//from ww  w. ja v  a 2 s .co  m
            parts.add(stringPart);
        } else {
            PartSource partSource = new ByteArrayPartSource(h.getFileName(), h.getBody());
            FilePart p = new FilePart(h.getPartName(), partSource);
            if (h.isContentTypeSet()) {
                p.setContentType(h.getContentType());
            }
            parts.add(p);
        }
    }
    return parts;
}