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:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST//from w  ww. j a  v a  2 s  . c o  m
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */

public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getUploadURL());
    String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.addTextBody("graph-uri", this.dataset);
    builder.addBinaryBody("res-file", owl);
    HttpEntity entity = builder.build();
    httppost.setEntity(entity);

    /*  THIS IS THE MULTIPART FORMAT WE NEED TO SEND.
            
    Content-Type: multipart/form-data; boundary=---------------------------32932166721282
    Content-Length: 234
            
    -----------------------------32932166721282
    Content-Disposition: form-data; name="graph-uri"
            
    http://www.kdl.ge.com/changeme
    -----------------------------32932166721282
    Content-Disposition: form-data; name="res-file"; filename="employee.owl"
    Content-Type: application/octet-stream
            
    <rdf:RDF
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:owl="http://www.w3.org/2002/07/owl#"
        xmlns="http://kdl.ge.com/pd/employee#"
        xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      .
      .
      .
    </rdf:RDF>
            
    -----------------------------32932166721282--
            
     */

    executeTestQuery();

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity resp_entity = response_http.getEntity();
    // get response with HTML tags removed
    String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " ");

    SimpleResultSet ret = new SimpleResultSet();

    if (responseTxt.trim().isEmpty()) {
        // success or bad login :-(
        ret.setSuccess(true);
    } else {
        ret.setSuccess(false);
        ret.addRationaleMessage(responseTxt);
    }
    resp_entity.getContent().close();
    return ret.toJson();
}

From source file:org.biopax.validator.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //from  www .ja va2  s. c o  m
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out
 * @throws IOException
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");

    //TODO add extra options (normalizer.fixDisplayName, normalizer.xmlBase)?

    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    HttpEntity httpEntity = meb.build();
    //       if(log.isDebugEnabled()) httpEntity.writeTo(System.err);
    String content = Executor.newInstance().execute(Request.Post(url).body(httpEntity)).returnContent()
            .asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a multipart upload request./*from   w w  w .j a v a  2 s  .co  m*/
 *
 * @param url the url
 * @param t the object to create
 * @param partName the name of the part
 * @param inputstream the file inputstream
 * @param contentType the type of the file to be attached
 * @return the http request
 * @throws UnsupportedEncodingException the unsupported encoding exception
 */
public <T> Attachment attachFile(String url, T t, String partName, InputStream inputstream, String contentType,
        String attachmentName) throws SmartsheetException {
    Util.throwIfNull(inputstream, contentType);
    Attachment attachment = null;
    final String boundary = "----" + System.currentTimeMillis();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(url));

    try {
        uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(t),
            ContentType.APPLICATION_JSON);
    builder.addBinaryBody("file", inputstream, ContentType.create(contentType), attachmentName);
    org.apache.http.HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    try {
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        attachment = this.getSmartsheet().getJsonSerializer()
                .deserializeResult(Attachment.class, responseEntity.getContent()).getResult();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return attachment;
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a resource using Smartsheet REST API.
 *
 * Exceptions:/*www . j av a 2s  . c o  m*/
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type
 * @param path the relative path of the resource collections
 * @param objectClass the resource object class
 * @param object the object to create
 * @return the created resource
 * @throws SmartsheetException the smartsheet exception
 */
protected <T> T createResourceWithAttachment(String path, Class<T> objectClass, T object, String partName,
        InputStream inputStream, String contentType, String attachmentName) throws SmartsheetException {
    Util.throwIfNull(path, object);
    Util.throwIfEmpty(path);

    HttpRequest request;
    final String boundary = "----" + System.currentTimeMillis();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(path));

    try {
        uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(object),
            ContentType.APPLICATION_JSON);
    builder.addBinaryBody("file", inputStream, ContentType.create(contentType), attachmentName);
    org.apache.http.HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    T obj = null;
    //implement switch case
    try {
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        obj = this.getSmartsheet().getJsonSerializer()
                .deserializeResult(objectClass, responseEntity.getContent()).getResult();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return obj;
}

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

@Override
protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input,
        String fileName, final long fileSize) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/* ww w .ja  v a2s . c o m*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");

    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 auth part to the multipart entity
    auth = StringUtils.trimToNull(auth);
    if (auth != null) {
        //StringBody authPart = new StringBody(
        //  auth, ContentType.create( "text/plain", getEncoding() ) );
        //b.addPart( "auth", authPart );
        b.addTextBody("auth", auth, ContentType.create("text/plain", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";
        //InputStreamBody filePart = new InputStreamBody( input, fileName );
        InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize);
        b.addPart("videofile", filePart);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.setHeader("MIME-Version", "1.0");
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept-Charset", "UTF-8");
    request.setHeader("Accept-Encoding", "gzip,deflate");
    request.setHeader("Connection", "close");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

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

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

    // create response
    return createResponse(response);
}

From source file:com.osbitools.ws.shared.web.BasicWebUtils.java

public WebResponse uploadFile(String path, String fname, InputStream in, String stoken)
        throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(path);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA);

    builder.addPart("fname", fn);
    builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname);

    BasicCookieStore cookieStore = new BasicCookieStore();

    if (stoken != null) {
        BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken);
        cookie.setDomain(TestConstants.JETTY_HOST);
        cookie.setPath("/");
        cookieStore.addCookie(cookie);/*w  ww.  j a v a 2s. c o  m*/
    }

    TestConstants.LOG.debug("stoken=" + stoken);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    HttpEntity entity = builder.build();

    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    String body;
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        body = handler.handleResponse(response);
    } catch (HttpResponseException e) {
        return new WebResponse(e.getStatusCode(), e.getMessage());
    }

    return new WebResponse(response.getStatusLine().getStatusCode(), body);
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Send data using HTTP POST method to the server named by vhost
 *
 * @param url address to request on the server
 * @param vhost name of the server at address which should respond. When null, localhost is assumed.
 * @param post data to send (name-value-pairs)
 * @param userName user name for HTTP authentication : only sent when requesting localhost
 * @param password encoded password for HTTP authentication : only sent when requesting localhost
 * @param usegzip if the body should be gzipped
 * @return response body//ww  w .j  a  va2 s  . c o m
 * @throws IOException when an error occurred
 */
public byte[] POSTbytes(final MultiProtocolURL url, final String vhost, final Map<String, ContentBody> post,
        final String userName, final String password, final boolean usegzip, final boolean concurrent)
        throws IOException {
    final HttpPost httpPost = new HttpPost(url.toNormalform(true));
    final boolean localhost = Domains.isLocalhost(url.getHost());
    if (!localhost)
        setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service
    if (vhost == null)
        setHost(Domains.LOCALHOST);

    final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    for (final Entry<String, ContentBody> part : post.entrySet())
        entityBuilder.addPart(part.getKey(), part.getValue());
    final HttpEntity multipartEntity = entityBuilder.build();
    // statistics
    this.upbytes = multipartEntity.getContentLength();

    if (usegzip) {
        httpPost.setEntity(new GzipCompressingEntity(multipartEntity));
    } else {
        httpPost.setEntity(multipartEntity);
    }

    if (!localhost || password == null) {
        return getContentBytes(httpPost, Integer.MAX_VALUE, concurrent);
    }

    byte[] content = null;

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", url.getPort()),
            new UsernamePasswordCredentials(userName, password));

    /* Use the custom YaCyDigestScheme for HTTP Digest Authentication */
    final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new YaCyDigestSchemeFactory()).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).build();

    try {
        this.httpResponse = httpclient.execute(httpPost);
        try {
            HttpEntity httpEntity = this.httpResponse.getEntity();
            if (httpEntity != null) {
                if (getStatusCode() == HttpStatus.SC_OK) {
                    content = getByteArray(httpEntity, Integer.MAX_VALUE);
                }
                // Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
                EntityUtils.consume(httpEntity);
            }
        } finally {
            this.httpResponse.close();
        }
    } finally {
        httpclient.close();
    }
    return content;
}

From source file:com.liferay.sync.engine.session.Session.java

private HttpEntity _getEntity(Map<String, Object> parameters) throws Exception {

    Path deltaFilePath = (Path) parameters.get("deltaFilePath");
    Path filePath = (Path) parameters.get("filePath");
    String zipFileIds = (String) parameters.get("zipFileIds");
    Path zipFilePath = (Path) parameters.get("zipFilePath");

    MultipartEntityBuilder multipartEntityBuilder = _getMultipartEntityBuilder(parameters);

    if (deltaFilePath != null) {
        multipartEntityBuilder.addPart("deltaFile", _getFileBody(deltaFilePath,
                (String) parameters.get("mimeType"), (String) parameters.get("title")));
    } else if (filePath != null) {
        multipartEntityBuilder.addPart("file",
                _getFileBody(filePath, (String) parameters.get("mimeType"), (String) parameters.get("title")));
    } else if (zipFileIds != null) {
        return _getURLEncodedFormEntity(parameters);
    } else if (zipFilePath != null) {
        multipartEntityBuilder.addPart("zipFile",
                _getFileBody(zipFilePath, "application/zip", String.valueOf(zipFilePath.getFileName())));
    }//w ww.  j a va  2 s.  c  o m

    return multipartEntityBuilder.build();
}

From source file:org.phenotips.integration.medsavant.internal.JsonMedSavantServer.java

@Override
public boolean uploadVCF(Patient patient) {
    HttpPost method = null;//from   ww w  . j a  v  a 2s .  c om
    try {
        MultipartEntityBuilder data = MultipartEntityBuilder.create();
        PatientData<String> identifiers = patient.getData("identifiers");
        String url = getMethodURL("UploadManager", "upload");
        String eid = identifiers.get("external_id");
        XWikiContext context = Utils.getContext();
        XWikiDocument doc = context.getWiki().getDocument(patient.getDocument(), context);
        method = new HttpPost(url);

        boolean hasData = false;
        for (XWikiAttachment attachment : doc.getAttachmentList()) {
            if (StringUtils.endsWithIgnoreCase(attachment.getFilename(), ".vcf")
                    && isCorrectVCF(attachment, eid, context)) {
                data.addBinaryBody(patient.getId() + ".vcf", attachment.getContentInputStream(context));
                hasData = true;
            }
        }
        if (hasData) {
            method.setEntity(data.build());
            this.client.execute(method).close();
            return true;
        }
    } catch (Exception ex) {
        this.logger.warn("Failed to upload VCF for patient [{}]: {}", patient.getDocument(), ex.getMessage(),
                ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return false;
}

From source file:nzilbb.bas.BAS.java

/**
 * Invoke the Pho2Syl service to syllabify a phonemic transcription.
 * @param lng <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language.
 * @param i Phonemic transcription of the utterance to be segmented. Format is a <a href="http://www.bas.uni-muenchen.de/forschung/Bas/BasFormatseng.html">BAS Partitur Format (BPF)</a> file with a KAN tier.
 * @param tier Name of tier in the annotation file, whose content is to be syllabified.
 * @param wsync Whether each word boundary is considered as syllable boundary.
 * @param oform Output format://w  ww. j  a v a2s . c  o  m
 *  <ul>
 *   <li>"bpf" - BAS Partiture format</li> 
 *   <li>"tg" - TextGrid format</li>
 *  </ul>
 * @param rate Only needed if <var>oform</var> = "tg" (TextGrid); Sample rate to convert sample values from BAS partiture file to seconds in TextGrid. 
 * @return The response to the request.
 * @throws IOException If an IO error occurs.
 * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured.
 */
public BASResponse Pho2Syl(String lng, InputStream i, String tier, Boolean wsync, String oform, Integer rate)
        throws IOException, ParserConfigurationException {
    HttpPost request = new HttpPost(getPho2SylUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("lng", languageTagger.tag(lng))
            .addBinaryBody("i", i, ContentType.create("text/plain-bas"), "BAS.par").addTextBody("tier", tier)
            .addTextBody("oform", oform);
    if (wsync != null)
        builder.addTextBody("wsync", wsync ? "yes" : "no");
    if (rate != null)
        builder.addTextBody("rate", rate.toString());
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}