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:com.ephesoft.dcma.batch.status.StatusConveyor.java

/**
 * Notifies any service event to fired on current server but needs to be handled by the server under which the service is
 * registered. It hits the particular server with the details required and registered server handles it respectively.
 * //from  w  w  w  . j av  a 2s .  c o  m
 * @param paramMap {@link Map<String, String>} details to be send to the server.
 * @param serviceType {@link ServiceType} type of service.
 */
public void notifyServiceEvent(final Map<String, String> paramMap, final ServiceType serviceType) {
    if (null != serviceType) {
        LOGGER.debug(EphesoftStringUtil.concatenate("Notifying server for service: ", serviceType.toString()));
        final String notifyWebServiceUrl = getNotifyWebServiceUrl(serviceType);
        if (null != notifyWebServiceUrl && !notifyWebServiceUrl.isEmpty()) {
            final HttpClient httpClient = new HttpClient();
            final PostMethod postMethod = new PostMethod(notifyWebServiceUrl);
            Part[] partArray = null;
            int index = 0;

            // If the details are to be send to web service
            if (null == paramMap || paramMap.isEmpty()) {
                partArray = new Part[1];
            } else {
                LOGGER.debug(EphesoftStringUtil.concatenate("Parameter passed are: ", paramMap.toString()));
                partArray = new Part[(paramMap.size() + 1)];
                final Iterator<String> keyIterator = paramMap.keySet().iterator();
                String key = null;
                while (keyIterator.hasNext()) {
                    key = keyIterator.next();
                    partArray[index] = new StringPart(key, paramMap.get(key));
                    index++;
                }
            }

            // Type of service which is a required parameter to be send
            partArray[index] = new StringPart(ICommonConstants.SERVICE_TYPE_PARAMETER,
                    String.valueOf(serviceType.getServiceType()));
            MultipartRequestEntity entity = new MultipartRequestEntity(partArray, postMethod.getParams());
            postMethod.setRequestEntity(entity);
            try {
                int statusCode = httpClient.executeMethod(postMethod);

                if (statusCode == STATUS_OK) {
                    LOGGER.debug(EphesoftStringUtil.concatenate(
                            "Server was notified successfully for service: ", serviceType.toString()));
                } else {
                    LOGGER.error(
                            EphesoftStringUtil.concatenate("Server was not able to be notified for service: ",
                                    serviceType.toString(), " and status code: ", statusCode));
                }
            } catch (HttpException httpException) {
                LOGGER.error(
                        EphesoftStringUtil.concatenate("Could not connect to server for notifying service: ",
                                serviceType.toString(), ICommonConstants.SPACE, httpException.getMessage()));
            } catch (IOException ioException) {
                LOGGER.error(
                        EphesoftStringUtil.concatenate("Could not connect to server for notifying service: ",
                                serviceType.toString(), ICommonConstants.SPACE, ioException.getMessage()));
            }
        }
    }
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static PutMethod sendMultipartPutRequest(String url, String body) throws IOException {
    HttpClient httpClient = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    // our handlers ignore key...so we can put anything here
    Part[] parts = { new StringPart("body", body) };
    putMethod.setRequestEntity(new MultipartRequestEntity(parts, putMethod.getParams()));
    httpClient.executeMethod(putMethod);
    return putMethod;

}

From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java

private MockHttpServletRequest getMultipartRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    byte[] fileContent = new byte[] { 1, 2, 3 };
    Part[] parts = new Part[] { new FilePart("file1", new ByteArrayPartSource("file1", fileContent)) };
    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());
    // Serialize request body
    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(requestContent);
    // Set request body to HTTP servlet request
    request.setContent(requestContent.toByteArray());
    // Set content type to HTTP servlet request (important, includes Mime boundary string)
    request.setContentType(multipartRequestEntity.getContentType());
    request.setMethod("POST");
    return request;
}

From source file:de.laeubisoft.tools.ant.validation.W3CCSSValidationTask.java

/**
 * Creates the actual request to the validation server for a given
 * {@link URL} and returns an inputstream the result can be read from
 * //from   w ww  .  ja  v  a 2 s .  c  om
 * @param uriToCheck
 *            the URL to check (or <code>null</code> if text or file should
 *            be used as input
 * @return the stream to read the response from
 * @throws IOException
 *             if unrecoverable communication error occurs
 * @throws BuildException
 *             if server returned unexspected results
 */
private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT));
    if (uriToCheck != null) {
        params.add(new NameValuePair("uri", uriToCheck.toString()));
    } else {
        if (text != null) {
            params.add(new NameValuePair("text", text));
        }
    }
    if (usermedium != null) {
        params.add(new NameValuePair("usermedium", usermedium));
    }
    if (profile != null) {
        params.add(new NameValuePair("profile", profile));
    }
    if (lang != null) {
        params.add(new NameValuePair("lang", lang));
    }
    if (warning != null) {
        params.add(new NameValuePair("warning", warning));
    }
    HttpClient httpClient = new HttpClient();
    HttpMethodBase method;
    if (uriToCheck != null) {
        //URIs must be checked via traditonal GET...
        GetMethod getMethod = new GetMethod(validator);
        getMethod.setQueryString(params.toArray(new NameValuePair[0]));
        method = getMethod;
    } else {
        PostMethod postMethod = new PostMethod(validator);
        if (text != null) {
            //Text request must be multipart encoded too...
            postMethod.setRequestEntity(new MultipartRequestEntity(Tools.nvToParts(params).toArray(new Part[0]),
                    postMethod.getParams()));
        } else {
            //Finally files must be checked with multipart-forms....
            postMethod.setRequestEntity(
                    Tools.createFileUpload(file, "file", null, params, postMethod.getParams()));
        }
        method = postMethod;
    }
    int result = httpClient.executeMethod(method);
    if (result == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    } else {
        throw new BuildException("Server returned " + result + " " + method.getStatusText());
    }

}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Client call to upload the run back to the originating server.
 * This method does nothing if the run is local.
 * @param runId The id of the run//from   ww w .  jav  a 2 s.  co  m
 * @throws IOException If the upload fails
 */
public static void uploadIfOrigin(String runId) throws IOException {

    // 1. Check origin
    File originFile = new File(
            Config.OUT_DIR + File.separator + runId + File.separator + "META-INF" + File.separator + "origin");

    if (!originFile.isFile())
        return; // Is local run, do nothing.

    String originSpec = readStringFromFile(originFile);
    int idx = originSpec.lastIndexOf('.');
    if (idx == -1) { // This is wrong, we do not accept this.
        logger.severe("Bad origin spec.");
        return;
    }
    idx = originSpec.lastIndexOf('.', idx - 1);
    if (idx == -1) {
        logger.severe("Bad origin spec.");
        return;
    }

    String host = originSpec.substring(0, idx);
    String key = null;
    URL target = null;
    String proxyHost = null;
    int proxyPort = -1;

    // Search the poll hosts for this origin.
    for (int i = 0; i < Config.pollHosts.length; i++) {
        Config.HostInfo pollHost = Config.pollHosts[i];
        if (host.equals(pollHost.name)) {
            key = pollHost.key;
            target = new URL(pollHost.url, "upload");
            proxyHost = pollHost.proxyHost;
            proxyPort = pollHost.proxyPort;
            break;
        }
    }

    if (key == null) {
        logger.severe("Origin host/url/key not found!");
        return;
    }

    // 2. Jar up the run
    String[] files = new File(Config.OUT_DIR, runId).list();
    File jarFile = new File(Config.TMP_DIR, runId + ".jar");
    jar(Config.OUT_DIR + runId, files, jarFile.getAbsolutePath());

    // 3. Upload the run
    ArrayList<Part> params = new ArrayList<Part>();
    //MultipartPostMethod post = new MultipartPostMethod(target.toString());
    params.add(new StringPart("host", Config.FABAN_HOST));
    params.add(new StringPart("key", key));
    params.add(new StringPart("origin", "true"));
    params.add(new FilePart("jarfile", jarFile));
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);
    PostMethod post = new PostMethod(target.toString());
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    if (proxyHost != null)
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status == HttpStatus.SC_FORBIDDEN)
        logger.severe("Server " + host + " denied permission to upload run " + runId + '!');
    else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
        logger.severe("Run " + runId + " origin error!");
    else if (status != HttpStatus.SC_CREATED)
        logger.severe(
                "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
    jarFile.delete();
}

From source file:edu.wustl.bulkoperator.client.BulkOperationServiceImpl.java

/**
 * This method will be called to start the bulk operation.
 * @param operationName operation name./*  w  w  w  .j  ava  2  s.  c  om*/
 * @param csvFile CSV file.
 * @param xmlTemplateFile XML template file.
 * @return Job Message.
 * @throws BulkOperationException BulkOperationException
 */
public JobMessage startbulkOperation(String operationName, File csvFile, File xmlTemplateFile)
        throws BulkOperationException {
    JobMessage jobMessage = null;
    if (!isLoggedIn) {
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.client.login.error"));
        return jobMessage;
    }

    PostMethod postMethod = new PostMethod(url + "/BulkHandler.do");
    try {
        Part[] parts = { new StringPart(OPERATION, operationName), new FilePart(TEMPLATE_FILE, xmlTemplateFile),
                new FilePart(CSV_FILE, csvFile) };
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        client.executeMethod(postMethod);

        InputStream inputStream = (InputStream) postMethod.getResponseBodyAsStream();
        ObjectInputStream oist = new ObjectInputStream(inputStream);
        Object object = oist.readObject();
        jobMessage = (JobMessage) object;

    } catch (FileNotFoundException exp) {
        List<String> listOfArguments = new ArrayList<String>();
        listOfArguments.add(xmlTemplateFile.getName());
        listOfArguments.add(csvFile.getName());
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.file.not.found", listOfArguments));
    } catch (IOException e) {
        List<String> listOfArguments = new ArrayList<String>();
        listOfArguments.add(xmlTemplateFile.getName());
        listOfArguments.add(csvFile.getName());
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.file.not.found", listOfArguments));
    } catch (ClassNotFoundException e) {
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("clz.not.found.error"));
    } finally {
        postMethod.releaseConnection();
    }
    return jobMessage;
}

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

@Test
public void testAdminUploadWithCsrfInFormField() 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 www  .  ja  v  a  2 s.  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()));
    Part csrfPart = new StringPart("csrfToken", csrfToken);
    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, csrfPart }, post.getParams()));
    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.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link PostMethod}
 * @throws javax.servlet.ServletException If something fails when uploading the content to the server
 *//*from w  w w . j  a v  a 2s .  c o m*/
@SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" })
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:jeeves.utils.XmlRequest.java

/** Sends the content of a file using a POST request and gets the response in
  * xml format./* www. j  a  v  a  2s . co  m*/
  */

public Element send(String name, File inFile) throws IOException, BadXmlResponseEx, BadSoapResponseEx {
    Part[] parts = new Part[alSimpleParams.size() + 1];

    int partsIndex = 0;

    parts[partsIndex] = new FilePart(name, inFile);

    for (NameValuePair nv : alSimpleParams)
        parts[++partsIndex] = new StringPart(nv.getName(), nv.getValue());

    PostMethod post = new PostMethod();
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    post.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
    post.setPath(address);
    post.setDoAuthentication(useAuthent());

    //--- execute request

    Element response = doExecute(post);

    if (useSOAP)
        response = soapUnembed(response);

    return response;
}

From source file:com.openkm.extension.servlet.ZohoServlet.java

/**
 *   //  w ww  .jav  a2 s.co  m
 */
private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang)
        throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException,
        IOException, OKMException {
    Map<String, String> result = new HashMap<String, String>();
    File tmp = null;

    try {
        String path = OKMRepository.getInstance().getNodePath(null, nodeUuid);
        String fileName = PathUtils.getName(path);
        tmp = File.createTempFile("okm", ".tmp");
        InputStream is = OKMDocument.getInstance().getContent(null, path, false);
        Document doc = OKMDocument.getInstance().getProperties(null, path);
        FileOutputStream fos = new FileOutputStream(tmp);
        IOUtils.copy(is, fos);
        fos.flush();
        fos.close();

        String id = UUID.randomUUID().toString();
        String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload";
        Part[] parts = { new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY),
                new StringPart("output", "url"), new StringPart("mode", "normaledit"),
                new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY),
                new StringPart("lang", lang), new StringPart("id", id),
                new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl) };

        PostMethod filePost = new PostMethod(zohoUrl);
        filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        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) {
            log.debug("OK: " + filePost.getResponseBodyAsString());
            ZohoToken zot = new ZohoToken();
            zot.setId(id);
            zot.setUser(getThreadLocalRequest().getRemoteUser());
            zot.setNode(nodeUuid);
            zot.setCreation(Calendar.getInstance());
            ZohoTokenDAO.create(zot);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                if (line.startsWith("URL=")) {
                    result.put("url", line.substring(4));
                    result.put("id", id);
                    break;
                }
            }

            rd.close();
        } else {
            String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString();
            log.error("ERROR: {}", error);
            throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error);
        }
    } finally {
        FileUtils.deleteQuietly(tmp);
    }

    return result;
}