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:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *//*from ww w .jav a  2s  .  c  om*/
@Test
public void testDoPost() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://www.ua.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:com.denimgroup.threadfix.cli.HttpRestUtils.java

public String httpPostFile(String request, File file, String[] paramNames, String[] paramVals) {

    Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    PostMethod filePost = new PostMethod(request);

    filePost.setRequestHeader("Accept", "application/json");

    try {/*from w  ww  .java  2  s .  co m*/
        Part[] parts = new Part[paramNames.length + 1];
        parts[paramNames.length] = new FilePart("file", file);

        for (int i = 0; i < paramNames.length; i++) {
            parts[i] = new StringPart(paramNames[i], paramVals[i]);
        }

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

        filePost.setContentChunked(true);
        HttpClient client = new HttpClient();
        int status = client.executeMethod(filePost);
        if (status != 200) {
            System.err.println("Status was not 200.");
        }

        InputStream responseStream = filePost.getResponseBodyAsStream();

        if (responseStream != null) {
            return IOUtils.toString(responseStream);
        }

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "There was an error and the POST request was not finished.";
}

From source file:com.bdaum.juploadr.uploadapi.locrrest.upload.LocrUpload.java

@Override
public boolean execute() throws ProtocolException, CommunicationException {
    HttpClient httpClient = HttpClientFactory.getHttpClient(getSession().getAccount());

    // checkAuthorization(client);
    this.monitor.uploadStarted(new UploadEvent(image, 0, true, false));

    PostMethod post = new PostMethod(POSTURL);
    List<Part> parts = getParts();
    MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            post.getParams());/* w w w.  j  a va2  s  .  co m*/
    post.setRequestEntity(entity);

    try {

        int status = httpClient.executeMethod(post);
        if (status == HttpStatus.SC_OK) {
            // deal with the response
            try {
                String response = post.getResponseBodyAsString();
                post.releaseConnection();
                boolean success = parseResponse(response);
                if (success) {
                    image.setState(UploadImage.STATE_UPLOADED);
                    ImageUploadResponse resp = new ImageUploadResponse(
                            ((LocrUploadResponseHandler) handler).getPhotoID());
                    this.monitor.uploadFinished(new UploadCompleteEvent(resp, image));

                } else {
                    throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$
                }

            } catch (IOException e) {
                // TODO: Is it safe to assume the upload failed here?
                this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$
                        + e.getMessage(), e);
            }
        } else {
            this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$
        }
    } catch (ConnectException ce) {
        this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$
    } catch (NoRouteToHostException route) {
        this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$
    } catch (UnknownHostException uhe) {
        this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$

    } catch (HttpException e) {
        this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$
    } catch (IOException e) {
        this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$
                + e, e);
    }
    return true;
}

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

/**
 * Execute the POST.//from  w  ww. ja  va 2 s  .  co m
 */
public void doPost(BaseResponse response) {
    PostMethod httppost = null;
    String theUrl = null;
    try {
        URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables);
        theUrl = url.toExternalForm();
        httppost = new PostMethod(url.toString());
        String requestBody = getBody();

        List<Part> parts = buildParts();

        httppost.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), httppost.getParams()));

        sendRequest(response, httppost, requestBody);
    } catch (MalformedURLException e) {
        LOG.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(e);
    } catch (Exception ex) {
        // logger.error(LogUtil.getLogMessage(ex.toString()), ex);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(ex);
    } finally {
        if (null != httppost) {
            httppost.releaseConnection();
        }
        if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) {
            LOG.info(
                    LogUtil.getLogMessage(
                            "Response from POST to " + theUrl + " got status code " + response.getHttpCode()
                                    + " BODY { " + response.getResponseBody() + " }",
                            LogEventType.Informational));
        }
    }

}

From source file:com.apatar.flickr.function.UploadPhotoFlickrTable.java

public List<KeyInsensitiveMap> execute(FlickrNode node, Hashtable<String, Object> values, String strApi,
        String strSecret) throws IOException, XmlRpcException {
    byte[] photo = (byte[]) values.get("photo");

    int size = values.size() + 2;

    values.remove("photo");

    File newFile = ApplicationData.createFile("flicr", photo);

    PostMethod post = new PostMethod("http://api.flickr.com/services/upload");
    Part[] parts = new Part[size];

    parts[0] = new FilePart("photo", newFile);
    parts[1] = new StringPart("api_key", strApi);
    int i = 2;// w ww  .  ja v a2  s  . co m
    for (String key : values.keySet())
        parts[i++] = new StringPart(key, values.get(key).toString());

    values.put("api_key", strApi);

    parts[i] = new StringPart("api_sig", FlickrUtils.Sign(values, strApi, strSecret));

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

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
        return null;
    } else {
        InputStream is = post.getResponseBodyAsStream();
        try {
            return createKeyInsensitiveMapFromElement(FlickrUtils.getRootElementFromInputStream(is));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.linkedin.pinot.server.realtime.ServerSegmentCompletionProtocolHandler.java

private SegmentCompletionProtocol.Response doHttp(SegmentCompletionProtocol.Request request, Part[] parts) {
    SegmentCompletionProtocol.Response response = new SegmentCompletionProtocol.Response(
            SegmentCompletionProtocol.ControllerResponseStatus.NOT_SENT, -1L);
    HttpClient httpClient = new HttpClient();
    ControllerLeaderLocator leaderLocator = ControllerLeaderLocator.getInstance();
    final String leaderAddress = leaderLocator.getControllerLeader();
    if (leaderAddress == null) {
        LOGGER.error("No leader found {}", this.toString());
        return new SegmentCompletionProtocol.Response(
                SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER, -1L);
    }/* ww  w  .j  a va2  s. co  m*/
    final String url = request.getUrl(leaderAddress);
    HttpMethodBase method;
    if (parts != null) {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        method = postMethod;
    } else {
        method = new GetMethod(url);
    }
    LOGGER.info("Sending request {} for {}", url, this.toString());
    try {
        int responseCode = httpClient.executeMethod(method);
        if (responseCode >= 300) {
            LOGGER.error("Bad controller response code {} for {}", responseCode, this.toString());
            return response;
        } else {
            response = new SegmentCompletionProtocol.Response(method.getResponseBodyAsString());
            LOGGER.info("Controller response {} for {}", response.toJsonString(), this.toString());
            if (response.getStatus().equals(SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER)) {
                leaderLocator.refreshControllerLeader();
            }
            return response;
        }
    } catch (IOException e) {
        LOGGER.error("IOException {}", this.toString(), e);
        leaderLocator.refreshControllerLeader();
        return response;
    }
}

From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java

@Nonnull
public <T> RestResponse<T> httpPostFile(@Nonnull String path, @Nonnull File file, @Nonnull String[] paramNames,
        @Nonnull String[] paramVals, @Nonnull Class<T> targetClass) {

    if (isUnsafeFlag())
        Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    String completeUrl = makePostUrl(path);
    if (completeUrl == null) {
        LOGGER.debug("The POST url could not be generated. Aborting request.");
        return ResponseParser
                .getErrorResponse("The POST url could not be generated and the request was not attempted.", 0);
    }//from  w  w  w. j a  v a  2s .com

    PostMethod filePost = new PostMethod(completeUrl);

    filePost.setRequestHeader("Accept", "application/json");

    RestResponse<T> response = null;
    int status = -1;

    try {
        Part[] parts = new Part[paramNames.length + 2];
        parts[paramNames.length] = new FilePart("file", file);
        parts[paramNames.length + 1] = new StringPart("apiKey", propertiesManager.getKey());

        for (int i = 0; i < paramNames.length; i++) {
            parts[i] = new StringPart(paramNames[i], paramVals[i]);
        }

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

        filePost.setContentChunked(true);
        HttpClient client = new HttpClient();
        status = client.executeMethod(filePost);

        if (status != 200) {
            LOGGER.warn("Request for '" + completeUrl + "' status was " + status + ", not 200 as expected.");
        }

        if (status == 302) {
            Header location = filePost.getResponseHeader("Location");
            printRedirectInformation(location);
        }

        response = ResponseParser.getRestResponse(filePost.getResponseBodyAsStream(), status, targetClass);

    } catch (SSLHandshakeException sslHandshakeException) {

        importCert(sslHandshakeException);

    } catch (IOException e1) {
        LOGGER.error("There was an error and the POST request was not finished.", e1);
        response = ResponseParser.getErrorResponse("There was an error and the POST request was not finished.",
                status);
    }

    return response;
}

From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java

/**
 * //from   w w  w. j  ava  2  s  .c  o m
 * 
 * @param filename
 */
public void upload(String filename, QQUser user) {
    HttpClient client = new HttpClient();
    HostConfiguration conf = new HostConfiguration();
    conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD);
    client.setHostConfiguration(conf);
    PostMethod method = new PostMethod("/cgi-bin/cface/upload");
    method.addRequestHeader("Accept", "*/*");
    method.addRequestHeader("Pragma", "no-cache");

    StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ()));
    uid.setContentType(null);
    uid.setTransferEncoding(null);

    //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7");
    //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040");
    StringPart clientkey = new StringPart("clientkey",
            "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67");
    //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16");
    //      StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey()));
    clientkey.setContentType(null);
    clientkey.setTransferEncoding(null);

    //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875");
    //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62");
    //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA");
    StringPart sign = new StringPart("sign",
            "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764");
    sign.setContentType(null);
    sign.setTransferEncoding(null);

    FilePart file;
    try {
        file = new FilePart("customfacefile", filename, new File(filename));
    } catch (FileNotFoundException e) {
        return;
    }

    Part[] parts = new Part[] { uid, clientkey, sign, file };
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());

    method.setRequestEntity(entity);
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            Header header = method.getResponseHeader("CFace-Msg");
            System.out.println(header.getValue());
            header = method.getResponseHeader("CFace-RetCode");
            System.out.println(header.getValue());
        }
    } catch (HttpException e) {
        return;
    } catch (IOException e) {
        return;
    } finally {
        method.releaseConnection();
    }
}

From source file:fr.opensagres.xdocreport.remoting.converter.server.ConverterServiceTestCase.java

@Test
public void convertPDF() throws Exception {

    PostMethod post = new PostMethod("http://localhost:" + PORT + "/convert");

    String ct = "multipart/mixed";
    post.setRequestHeader("Content-Type", ct);
    Part[] parts = new Part[4];
    String fileName = "ODTCV.odt";

    parts[0] = new FilePart("document", new File(root, fileName), "application/vnd.oasis.opendocument.text",
            "UTF-8");
    parts[1] = new StringPart("outputFormat", ConverterTypeTo.PDF.name());
    parts[2] = new StringPart("via", ConverterTypeVia.ODFDOM.name());
    parts[3] = new StringPart("download", "true");
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient httpclient = new HttpClient();

    try {//  w  w  w  . ja v a2  s .c o  m
        int result = httpclient.executeMethod(post);
        Assert.assertEquals(200, result);
        Assert.assertEquals("attachment; filename=\"ODTCV_odt.pdf\"",
                post.getResponseHeader("Content-Disposition").getValue());

        byte[] convertedDocument = post.getResponseBody();
        Assert.assertNotNull(convertedDocument);

        File outFile = new File("target/ODTCV_odt.pdf");
        outFile.getParentFile().mkdirs();
        IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile));

    } finally {

        post.releaseConnection();
    }
}

From source file:com.zimbra.cs.client.soap.LmcSendMsgRequest.java

public String postAttachment(String uploadURL, LmcSession session, File f, String domain, // cookie domain e.g. ".example.zimbra.com"
        int msTimeout) throws LmcSoapClientException, IOException {
    String aid = null;/*from  w ww. j  a  v a  2  s .  c  o m*/

    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread()
                + " LmcSendMsgRequest.postAttachment session=null");

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(uploadURL);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        HttpState initialState = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            Cookie cookie = new Cookie(domain, ck.getKey(), ck.getValue(), "/", -1, false);
            initialState.addCookie(cookie);
        }
        client.setState(initialState);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    post.getParams().setSoTimeout(msTimeout);
    int statusCode = -1;
    try {
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName());
        Part[] parts = { new FilePart(f.getName(), f, contentType, "UTF-8") };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        statusCode = HttpClientUtil.executeMethod(client, post);

        // parse the response
        if (statusCode == 200) {
            // paw through the returned HTML and get the attachment id
            String response = post.getResponseBodyAsString();
            //System.out.println("response is\n" + response);
            int lastQuote = response.lastIndexOf("'");
            int firstQuote = response.indexOf("','") + 3;
            if (lastQuote == -1 || firstQuote == -1)
                throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response);
            aid = response.substring(firstQuote, lastQuote);
        } else {
            throw new LmcSoapClientException("Attachment post failed, status=" + statusCode);
        }
    } catch (IOException e) {
        System.err.println("Attachment post failed");
        e.printStackTrace();
        throw e;
    } finally {
        post.releaseConnection();
    }

    return aid;
}