Example usage for org.apache.http.entity.mime MultipartEntityBuilder build

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntityBuilder build.

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:ConnectionProtccol.HttpsClient.java

/**
 *
 * @param urlParams//w  w w  . j a va 2  s  .co  m
 * @param postParams
 * 
 */
public boolean httpsPost(String url, MultipartEntityBuilder builder, UrlEncodedFormEntity formParams) {

    loggerObj.log(Level.INFO, "Inside httpsPost method");
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        //  HttpPost httppost = new HttpPost("https://reportsapi.zoho.com/api/harshavardhan.r@zohocorp.com/Test/Name_password?ZOHO_ACTION=IMPORT&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=7ed717b94bc30455aad11ce5d31d34f9&ZOHO_API_VERSION=1.0");
        loggerObj.log(Level.INFO, "Going to post to the zoho reports api");

        HttpPost httppost = new HttpPost(url);

        //Need to understand the difference betwween multipartentitybuilder and urlencodedformentity//
        HttpEntity entity = null;
        if (builder != null)
            entity = builder.build();

        if (formParams != null)
            entity = formParams;

        httppost.setEntity(entity);
        loggerObj.log(Level.INFO, "executing request");
        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException ex) {
            loggerObj.log(Level.INFO, "Cannot connect to reports.zoho.com" + ex.toString());
            return false;
        }
        try {
            loggerObj.log(Level.INFO, "----------------------------------------");
            loggerObj.log(Level.INFO, response.toString());
            response.getStatusLine();
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                loggerObj.log(Level.INFO, "Response content length: " + resEntity.getContentLength());
                BufferedReader rd = null;
                try {
                    rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                } catch (IOException ex) {
                    loggerObj.log(Level.INFO,
                            "cannot read the response 1 from reports.zoho.com" + ex.toString());
                    return false;
                } catch (UnsupportedOperationException ex) {
                    loggerObj.log(Level.INFO, "cannot read the response 2" + ex.toString());
                    return false;
                }
                String line = "";
                try {
                    loggerObj.log(Level.INFO, "reading response line");
                    while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                        loggerObj.log(Level.INFO, line);
                    }
                } catch (IOException ex) {
                    loggerObj.log(Level.INFO, "cannot read the response 3" + ex.toString());
                    return false;
                }
            }
            try {
                EntityUtils.consume(resEntity);
            } catch (IOException ex) {
                loggerObj.log(Level.INFO, "cannot read the response 4" + ex.toString());
                return false;
            }
        } finally {
            try {
                response.close();
            } catch (IOException ex) {
                loggerObj.log(Level.INFO, "cannot close the response" + ex.toString());
                return false;
            }
        }
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            loggerObj.log(Level.INFO, "cannot read the https clinet" + ex.toString());
            return false;
        }
    }
    return true;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Create a multipart form//  ww w  .jav a 2  s  . c  om
 * 
 * @param request
 *            Request object
 * @param keyVals
 *            Key and value pairs, the even(begins with 0) position params
 *            are key and the odds are values
 * @return
 */
public static HttpUriRequest multipartForm(HttpPost request, Object... keyVals) {
    if (request == null || ValidationUtils.isEmpty(keyVals))
        return request;
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    boolean hasVal = false;

    String key;
    for (int i = 0; i < keyVals.length; i += 2) {
        key = ShenStrings.str(keyVals[i]);
        hasVal = i + 1 < keyVals.length;

        if (!hasVal || keyVals[i + 1] == null) {
            builder.addTextBody(key, StringUtils.EMPTY, CONTENT_TYPE_PLAIN_TEXT);
            break;
        }

        if (keyVals[i + 1].getClass().isAssignableFrom(File.class)) {
            builder.addPart(key, new FileBody((File) keyVals[i + 1]));
        } else {
            builder.addTextBody(key, keyVals[i + 1].toString(), CONTENT_TYPE_PLAIN_TEXT);
        }
    }
    request.setEntity(builder.build());
    return request;
}

From source file:edu.si.services.sidora.rest.batch.BatchServiceTest.java

@Test
public void newBatchRequest_addResourceObjects_Test() throws Exception {

    String resourceListXML = FileUtils
            .readFileToString(new File("src/test/resources/test-data/batch-test-files/audio/audioFiles.xml"));

    String expectedHTTPResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<Batch>\n" + "    <ParentPID>" + parentPid + "</ParentPID>\n" + "    <CorrelationID>"
            + correlationId + "</CorrelationID>\n" + "</Batch>\n";

    BatchRequestResponse expectedCamelResponseBody = new BatchRequestResponse();
    expectedCamelResponseBody.setParentPID(parentPid);
    expectedCamelResponseBody.setCorrelationId(correlationId);

    MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
    mockEndpoint.expectedMessageCount(1);

    context.getComponent("sql", SqlComponent.class).setDataSource(db);
    context.getRouteDefinition("BatchProcessResources").autoStartup(false);

    //Configure and use adviceWith to mock for testing purpose
    context.getRouteDefinition("BatchProcessAddResourceObjects").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override// w w w.j av a 2s.  c o m
                public void configure() throws Exception {
                    weaveById("httpGetResourceList").replace().setBody(simple(resourceListXML));

                    weaveByToString(".*bean:batchRequestControllerBean.*").replace().setHeader("correlationId",
                            simple(correlationId));

                    weaveAddLast().to("mock:result");

                }
            });

    HttpPost post = new HttpPost(BASE_URL + "/addResourceObjects/" + parentPid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);

    // Add filelist xml URL upload
    builder.addTextBody("resourceFileList", resourceFileList, ContentType.TEXT_PLAIN);
    // Add metadata xml file URL upload
    builder.addTextBody("ds_metadata", ds_metadata, ContentType.TEXT_PLAIN);
    // Add sidora xml URL upload
    builder.addTextBody("ds_sidora", ds_sidora, ContentType.TEXT_PLAIN);
    // Add association xml URL upload
    builder.addTextBody("association", association, ContentType.TEXT_PLAIN);
    // Add resourceOwner string
    builder.addTextBody("resourceOwner", resourceOwner, ContentType.TEXT_PLAIN);

    post.setEntity(builder.build());

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    String responseBody = EntityUtils.toString(response.getEntity());
    log.debug("======================== [ RESPONSE ] ========================\n" + responseBody);

    assertEquals(expectedHTTPResponseBody, responseBody);

    log.debug("===============[ DB Requests ]================\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchRequests"));
    log.debug("===============[ DB Resources ]===============\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchResources"));

    BatchRequestResponse camelResultBody = (BatchRequestResponse) mockEndpoint.getExchanges().get(0).getIn()
            .getBody();

    assertIsInstanceOf(BatchRequestResponse.class, camelResultBody);
    assertEquals(camelResultBody.getParentPID(), parentPid);
    assertEquals(camelResultBody.getCorrelationId(), correlationId);

    assertMockEndpointsSatisfied();

}

From source file:org.exmaralda.webservices.BASChunkerConnector.java

public String callChunker(File bpfInFile, File audioFile, HashMap<String, Object> otherParameters)
        throws IOException, JDOMException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println("Chunker called at " + dateFormat.format(date)); //2016/11/16 12:08:43        System.out.println("Chunker called at " + Date.);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (otherParameters != null) {
        builder.addTextBody("language", (String) otherParameters.get("language"));
    }/* w w w. j a  v  a2 s.co m*/

    builder.addTextBody("aligner", "fast");
    builder.addTextBody("force", "rescue");
    builder.addTextBody("minanchorlength", "2");
    builder.addTextBody("boost_minanchorlength", "3");

    // add the text file
    builder.addBinaryBody("bpf", bpfInFile);

    // add the audio file
    builder.addBinaryBody("audio", audioFile);

    System.out.println("All parameters set. ");

    // construct a POST request with the multipart entity
    HttpPost httpPost = new HttpPost(chunkerURL);
    httpPost.setEntity(builder.build());

    System.out.println("URI: " + httpPost.getURI().toString());

    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity result = response.getEntity();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode == 200 && result != null) {
        String resultAsString = EntityUtils.toString(result);

        /*
        <WebServiceResponseLink>
            <success>true</success>
            <downloadLink>https://clarin.phonetik.uni-muenchen.de:443/BASWebServices/data/2019.01.03_15.58.41_9D4EECAD0791F9E9ED16DF35E66D1485/IDS_ISW_Chunker_Test_16kHz_OHNE_ANFANG.par</downloadLink>
            <output/>
            <warnings/>
        </WebServiceResponseLink>
        */

        // read the XML result string
        Document doc = FileIO.readDocumentFromString(resultAsString);

        // check if success == true
        Element successElement = (Element) XPath.selectSingleNode(doc, "//success");
        if (!((successElement != null) && successElement.getText().equals("true"))) {
            String errorText = "Call to BASChunker was not successful: "
                    + IOUtilities.elementToString(doc.getRootElement(), true);
            throw new IOException(errorText);
        }

        Element downloadLinkElement = (Element) XPath.selectSingleNode(doc, "//downloadLink");
        String downloadLink = downloadLinkElement.getText();

        // now we have the download link - just need to get the content as text
        String bpfOutString = downloadText(downloadLink);

        EntityUtils.consume(result);
        httpClient.close();

        return bpfOutString;
        //return resultAsString;
    } else {
        // something went wrong, throw an exception
        String reason = statusLine.getReasonPhrase();
        throw new IOException(reason);
    }

}

From source file:org.syncany.plugins.php.PhpTransferManager.java

@Override
public void upload(File localFile, RemoteFile remoteFile) throws StorageException {
    logger.info("Uploading: " + localFile.getName() + " to " + remoteFile.getName());
    try {/* www . ja va2  s.  c  o m*/
        final String remote_name = remoteFile.getName();
        final File f = localFile;
        int r = operate("upload", new IPost() {
            List<NameValuePair> _nvps;

            public void mutateNVPS(List<NameValuePair> nvps) throws Exception {
                _nvps = nvps;
                nvps.add(new BasicNameValuePair("filename", remote_name));
            }

            public int mutatePost(HttpPost p) throws Exception {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.addPart("file", new FileBody(f));
                Iterator<NameValuePair> it = _nvps.iterator();
                while (it.hasNext()) {
                    NameValuePair nvp = it.next();
                    builder.addTextBody(nvp.getName(), nvp.getValue());
                }
                p.setEntity(builder.build());
                return -1;
            }

            @Override
            public int consumeResponse(InputStream s) throws Exception {
                String response = getAnswer(s);
                if (response.equals("true")) {
                    return 1;
                } else {
                    throw new Exception(response);
                }
            }

        });
        if (r != 1) {
            throw new Exception("Unexpected error, result code = " + r);
        }

    } catch (Exception e) {
        throw new StorageException("Cannot upload file " + remoteFile, e);
    }
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * create HttpEntity for multi part file upload
 * @param file : file to upload, must be in class path
 * @param contentType/*from  ww  w  .  j  a v  a  2 s  . com*/
 * @return HttpEntity
 * @throws FileNotFoundException 
 */
private HttpEntity getMultiPartEntity(final File file, String formName) throws FileNotFoundException {
    InputStream is = null;
    if (file.exists()) {
        is = new FileInputStream(file);
    } else {
        LogHandler.warn("File not found, so trying to read it from class path now");
        is = HttpClient.class.getResourceAsStream(file.getPath());
    }
    if (null == formName) {
        formName = file.getName();
    }
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addBinaryBody(formName, is, ContentType.MULTIPART_FORM_DATA, file.getName());

    return builder.build();
}

From source file:com.buffalokiwi.api.API.java

/**
 * Perform a post-based request to some endpoint
 * @param url The URL//from w  ww.  j av  a  2 s .  c o m
 * @param formData Key/Value pairs to send
 * @param files Key/File files to send
 * @param headers Extra headers to send
 * @return response
 * @throws APIException If something goes wrong
 */
@Override
public IAPIResponse post(final String url, final List<NameValuePair> formData,
        final Map<String, PostFile> files, final Map<String, String> headers) throws APIException {
    final HttpPost post = (HttpPost) createRequest(HttpMethod.POST, url, headers);

    //..Create a multi-part form data entity
    final MultipartEntityBuilder b = MultipartEntityBuilder.create();

    //..Set the mode
    b.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    setMultipartFileData(files, b);

    //..Check for non-file form data
    setMultipartFormData(formData, b);

    //..Attach the form data to the post request
    post.setEntity(b.build());

    //..Execute the request
    return executeRequest(post);
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Should only be called from uploadLogs(). Compresses all files that belong
 to the given log set, and uploads all compressed files to the server. */
private boolean uploadLogs(final String logSet) {
    if (logSet == null)
        return false;

    File logsDir = getLogsDir();//from  www.j  a v a  2  s . c o  m
    if (logsDir == null)
        return false;
    gzipLogs(logsDir, logSet);

    // Uploading only gz'd files
    FilenameFilter gzFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".gz");
        }
    };
    File[] toUpload = logsDir.listFiles(gzFilter);

    String url = getUploadUrl();
    if (url == null) {
        /* This means the server is unable to accept the logs. */
        keepRecents(toUpload, 100);
        return false;
    }

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN));

    ContentType ct = ContentType.create("x-application/gzip");
    for (File f : toUpload) {
        entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName()));
    }
    post.setEntity(entity.build());

    boolean success = false;
    try (CloseableHttpResponse response = client.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        Log.log(Level.INFO, "Log upload result: {0}", status);
        if (status == HttpStatus.SC_OK) { // 200
            for (File f : toUpload) {
                try {
                    f.delete();
                } catch (SecurityException ex) {
                }
            }
            success = true;
        } else {
            LogRecord rec = new LogRecord(Level.INFO, "Server Err");
            rec.setParameters(new Object[] { url, "Status: " + status });
            getLogger().log(rec);
        }

        HttpEntity rspEntity = response.getEntity();
        EntityUtils.consume(rspEntity);
        client.close();
    } catch (IOException ex) {
        Log.log(ex);
    }

    keepRecents(toUpload, 100); // In case of exceptions or errors
    return success;
}