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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

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"));
    }//from   w  ww .  j  a  v a2  s.  c o 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:com.byteengine.client.Client.java

public void write(String token, String db, String remoteFile, InputStream data)
        throws ByteEngineException, IOException {

    String uploadTicket = getUploadTicket(token, db, remoteFile);

    CloseableHttpResponse response = null;
    try {/*ww  w  . j  av  a  2s. co m*/
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("uploading file with ticket %s", uploadTicket));
        }

        HttpPost post = new HttpPost(String.format("%s/bfs/writebytes/%s", serverBaseUrl, uploadTicket));
        setProxy(post);

        HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("file", data).build();
        post.setEntity(entity);

        response = httpClient.execute(post);

        String resp = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        JSONObject json = new JSONObject(resp);
        String status = json.getString("status");

        if (!"ok".equalsIgnoreCase(status)) {
            throw new ByteEngineException(json.getString("msg"));
        }
    } finally {
        try {
            data.close();
        } catch (IOException ioe) {
        }
        try {
            response.close();
        } catch (IOException ioe) {
        }
    }
}

From source file:io.swagger.client.api.CameraApi.java

/**
* Capture a photo/* w  ww  .java2 s.c  o m*/
* 
 * @return void
*/
public void capturePhotoPost() throws TimeoutException, ExecutionException, InterruptedException, ApiException {
    Object postBody = null;

    // create path and map variables
    String path = "/capture/photo".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody,
                headerParams, formParams, contentType, authNames);
        if (localVarResponse != null) {
            return;
        } else {
            return;
        }
    } catch (ApiException ex) {
        throw ex;
    } catch (InterruptedException ex) {
        throw ex;
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof VolleyError) {
            VolleyError volleyError = (VolleyError) ex.getCause();
            if (volleyError.networkResponse != null) {
                throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
            }
        }
        throw ex;
    } catch (TimeoutException ex) {
        throw ex;
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * Send a post request to the server to rank answers in the csvAnswerData
 * /*from w ww. j a v a 2 s.c om*/
 * @param client Authorized {@link HttpClient}
 * @param ranker_url URL of the ranker to hit. Ex.)
 *        https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/ rankers/{ranker_id}/rank
 * @param csvAnswerData A string with the answer data in csv form
 * @return JSONObject of the response from the server
 * @throws ClientProtocolException
 * @throws IOException
 * @throws HttpException
 * @throws JSONException
 */
public static JSONObject rankAnswers(CloseableHttpClient client, String ranker_url, String csvAnswerData)
        throws ClientProtocolException, IOException, HttpException, JSONException {

    // If there is no csv data return an empty array
    if (csvAnswerData.trim().equals("")) {
        return new JSONObject("{\"code\":200 , \"answers\" : []}");
    }
    // Create post request to rank answers
    HttpPost post = new HttpPost(ranker_url);
    MultipartEntityBuilder postParams = MultipartEntityBuilder.create();

    // Fill in post request data
    postParams.addPart(RetrieveAndRankConstants.ANSWER_DATA, new AnswerFileBody(csvAnswerData));
    post.setEntity(postParams.build());

    // Send post request and get resulting response
    HttpResponse response = client.execute(post);
    String responseString = RankerCreationUtil.getHttpResultString(response);
    JSONObject responseJSON = null;
    try {
        responseJSON = (JSONObject) JSON.parse(responseString);
    } catch (NullPointerException | JSONException e) {
        logger.error(e.getMessage());
    }
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new HttpException(responseString + ":" + post);
    }
    return responseJSON;
}

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 {/*from w  ww  . jav  a2s . 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:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;/*from   w w  w . j av  a2  s  . co  m*/
    String hashPassword = md5Custom(password);
    JSONObject jsObj = new JSONObject();
    jsObj.put("group", group);
    jsObj.put("newHash", hashPassword);

    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.updateGroupAccess", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    }

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:gda.util.ElogEntry.java

/**
 * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php"
 * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the
 * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be
 * either the development or production databases.
 * /*from  ww w.  j  a  va 2 s .c o m*/
 * @param title
 *            The ELog title
 * @param content
 *            The ELog content
 * @param userID
 *            The user ID e.g. epics or gda or abc12345
 * @param visit
 *            The visit number
 * @param logID
 *            The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11,
 *            BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall
 *            Coordinators, OM = Optics and Meteorology, OPR = Operations, E
 * @param groupID
 *            The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics
 *            and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line,
 * @param fileLocations
 *            The image file names with path to upload
 * @throws ELogEntryException
 */
public static void post(String title, String content, String userID, String visit, String logID, String groupID,
        String[] fileLocations) throws ELogEntryException {
    String targetURL = POST_UPLOAD_URL;
    try {
        String entryType = "41";// entry type is always a log (41)
        String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title;

        MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost)
                .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID)
                .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType)
                .addTextBody("txtUSERID", userID);

        if (fileLocations != null) {
            for (int i = 1; i < fileLocations.length + 1; i++) {
                File targetFile = new File(fileLocations[i - 1]);
                request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"),
                        targetFile.getName());
            }
        }

        HttpEntity entity = request.build();
        targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL);
        HttpPost httpPost = new HttpPost(targetURL);
        httpPost.setEntity(entity);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
            if (!responseString.contains("New Log Entry ID")) {
                throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode()
                        + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = "
                        + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = "
                        + entryType + " userID = " + userID);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    } catch (ELogEntryException e) {
        throw e;
    } catch (Exception e) {
        throw new ELogEntryException("Error in ELogger.  Database:" + targetURL, e);
    }
}

From source file:com.autonomy.aci.client.transport.impl.AciHttpClientImpl.java

/**
 * Create a {@code PostMethod} and adds the ACI parameters to the request body.
 * @param serverDetails The details of the ACI server the request will be sent to
 * @param parameters    The parameters to send with the ACI action.
 * @return An {@code HttpPost} that is ready to execute the ACI action.
 * @throws UnsupportedEncodingException Will be thrown if <tt>serverDetails.getCharsetName()</tt> returns a
 *                                      charset that is not supported by the JVM
 * @throws URISyntaxException           If there was a problem construction the request URI from the
 *                                      <tt>serverDetails</tt> and <tt>parameters</tt>
 *///w  w  w . jav  a  2s.com
private HttpUriRequest createPostMethod(final AciServerDetails serverDetails,
        final Set<? extends ActionParameter<?>> parameters)
        throws URISyntaxException, UnsupportedEncodingException {
    LOGGER.trace("createPostMethod() called...");

    // Create the URI to use...
    final URI uri = new URIBuilder()
            .setScheme(serverDetails.getProtocol().toString().toLowerCase(Locale.ENGLISH))
            .setHost(serverDetails.getHost()).setPort(serverDetails.getPort()).setPath("/").build();

    // Create the method...
    final HttpPost method = new HttpPost(uri);

    final Charset charset = Charset.forName(serverDetails.getCharsetName());

    final boolean requiresMultipart = parameters.stream().anyMatch(ActionParameter::requiresPostRequest);

    if (requiresMultipart) {
        final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(charset);

        parameters.forEach(parameter -> parameter.addToEntity(multipartEntityBuilder, charset));

        // Convert the parameters into an entity...
        method.setEntity(multipartEntityBuilder.build());
    } else {
        method.setEntity(new StringEntity(convertParameters(parameters, serverDetails.getCharsetName()),
                serverDetails.getCharsetName()));
    }

    // Return the method...
    return method;
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid
 * If the file is succesfully uploaded the response code of 204 is returned.
 * //  w  ww. j  ava 2  s  .  co  m
 * @param planUid 
 * @param sessionId
 * @param file
 * @return HTTP Response code as int
 * @throws Exception
 */

public int postFileAPI(String planUid, String sessionId, File file) throws Exception {

    int respCode;
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN);
    StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN);

    try {
        HttpPost httpPost = new HttpPost(ePoint + "/api/File");
        FileBody fb = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId)
                .addPart("sessionId", sId).build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            m_log.info("executing " + httpPost.getRequestLine());
            m_log.info(resp.getStatusLine());
            respCode = resp.getStatusLine().getStatusCode();
        } finally {
            resp.close();
        }

    } finally {
        httpClient.close();
    }

    return respCode;
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input,
        String fileName, String mimeType) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*from www  . j  av  a2s  .co  m*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add xml part to the multipart entity
    if (xml != null) {
        //InputStreamBody xmlPart = new InputStreamBody(
        //  new ByteArrayInputStream( xml.getBytes( getEncoding() ) ),
        //  ContentType.parse( "application/xml" ),
        //  "body.xml" );
        //b.addPart( "metadata", xmlPart );
        b.addTextBody("metadata", xml, ContentType.create("application/xml", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        mimeType = StringUtils.trimToNull(mimeType);
        if (mimeType == null)
            mimeType = "application/octet-stream";

        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";

        //InputStreamBody filePart = new InputStreamBody(
        //  input, ContentType.create( mimeType ), fileName );
        //b.addPart( "attachment", filePart );
        b.addBinaryBody("attachment", input, ContentType.create(mimeType), fileName);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept", "application/xml");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    getAuthConsumer().sign(request);

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}