Example usage for org.apache.http.entity FileEntity FileEntity

List of usage examples for org.apache.http.entity FileEntity FileEntity

Introduction

In this page you can find the example usage for org.apache.http.entity FileEntity FileEntity.

Prototype

public FileEntity(File file, ContentType contentType) 

Source Link

Usage

From source file:com.sayar.requests.RequestArguments.java

/**
 * Setter for the request entity. The file will be consumed by the request.
 * //from  www .  j a v a2  s . c  o  m
 * @param file
 * @param contentType
 */
public void setRequestEntity(final File file, final String contentType) {
    this.requestEntity = new FileEntity(file, contentType);
}

From source file:org.mule.jenkins.Helper.java

public JobInfo copyFromJob(String newJobName, String fromJobName) throws JenkinsConnectorException {
    HttpPost method = new HttpPost(
            getUrl() + "/createItem?name=" + newJobName + "&mode=copy&from=" + fromJobName);
    File configFile = new File(Helper.class.getClassLoader().getResource("config.xml").getPath());
    JobInfo rJobInfo = new JobInfo();

    try {//w ww. ja va  2  s.  co  m
        FileEntity fileentity = new FileEntity(configFile, "application/xml");
        BufferedHttpEntity reqEntity = new BufferedHttpEntity(fileentity);
        method.setEntity(reqEntity);

        HttpResponse response = client.execute(method, context);

        if (response.getStatusLine().getStatusCode() != 302) {
            EntityUtils.consume(response.getEntity());
            throw new JenkinsConnectorException("copyFromJob response status error", "",
                    response.getStatusLine().getStatusCode() + " "
                            + response.getStatusLine().getReasonPhrase());
        }

        EntityUtils.consume(response.getEntity());

        rJobInfo = getJenkinsJobInfo(newJobName);

    } catch (Exception e) {
        throw new JenkinsConnectorException("copyFromJob http request failed", "", "", e);
    }

    return rJobInfo;
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendFile(File file, ContentTypeVS contentTypeVS, String serverURL, String... headerNames) {
    log.info("sendFile - contentType: " + contentTypeVS + " - serverURL: " + serverURL);
    ResponseVS responseVS = null;//  w  ww  .j  av a 2s. c o  m
    HttpPost httpPost = null;
    ContentTypeVS responseContentType = null;
    CloseableHttpResponse response = null;
    try {
        httpPost = new HttpPost(serverURL);
        ContentType contentType = null;
        if (contentTypeVS != null)
            contentType = ContentType.create(contentTypeVS.getName());
        FileEntity entity = new FileEntity(file, contentType);
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - connManager stats: "
                + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        if (headerNames != null) {
            List<String> headerValues = new ArrayList<String>();
            for (String headerName : headerNames) {
                org.apache.http.Header headerValue = response.getFirstHeader(headerName);
                headerValues.add(headerValue.getValue());
            }
            responseVS.setData(headerValues);
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Uploads a set of given files with a specified dataset name.
 * /*from  ww  w  .ja  va  2 s.  c  om*/
 * @param url
 *            the query url
 * @param file
 *            the file to be uploaded
 * @param cookie
 *            the cookie to be set in the request
 * @return the HTTP Response
 */
public ClientURLResponse postFile(String url, File file, String cookie) {
    HttpPut httpput = new HttpPut(url);
    httpput.setHeader("Content-Type", "application/octet-stream");
    FileEntity fileEntity = new FileEntity(file, "binary/octet-stream");
    fileEntity.setChunked(false);
    httpput.setEntity(fileEntity);
    return execute(httpput, cookie);
}

From source file:edu.lternet.pasta.client.DataPackageManagerClient.java

/**
 * Executes the 'evaluateDataPackage' web service method.
 * /*from   ww w .j  a  v a 2  s.  c om*/
 * @param emlFile
 *          the Level-0 EML document describing the data package to be
 *          evaluated
 * @return a string holding the XML quality report document resulting from the
 *         evaluation
 * @see <a target="top"
 *      href="http://package.lternet.edu/package/docs/api">Data Package
 *      Manager web service API</a>
 */
public String evaluateDataPackage(File emlFile) throws Exception {
    String serviceMethod = "evaluateDataPackage";
    String contentType = "application/xml";
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(BASE_URL + "/evaluate/eml");
    String qualityReport = null;

    // Set header content
    if (this.token != null) {
        httpPost.setHeader("Cookie", "auth-token=" + this.token);
    }
    httpPost.setHeader("Content-Type", contentType);

    // Set the request entity
    HttpEntity fileEntity = new FileEntity(emlFile, ContentType.create(contentType));
    httpPost.setEntity(fileEntity);

    try {
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        String entityString = EntityUtils.toString(httpEntity);

        if (statusCode == HttpStatus.SC_ACCEPTED) {
            String transactionId = entityString;
            EmlPackageId emlPackageId = EmlUtility.emlPackageIdFromEML(emlFile);

            if (emlPackageId != null) {
                EmlPackageIdFormat epif = new EmlPackageIdFormat();
                String packageId = epif.format(emlPackageId);
                String scope = emlPackageId.getScope();
                Integer identifier = emlPackageId.getIdentifier();
                Integer revision = emlPackageId.getRevision();
                Integer idleTime = 0;

                /*
                 * Initial sleep period to mitigate potential error-check race condition
                 */
                Thread.sleep(initialSleepTime);

                while (idleTime <= maxIdleTime) {
                    logIdleTime(serviceMethod, emlPackageId.toString(), idleTime);

                    try {
                        String errorText = readDataPackageError(transactionId);
                        throw new Exception(errorText);
                    } catch (ResourceNotFoundException e) {
                        /*
                         * The transactionId is no longer found, so the transaction has completed.
                         */
                        logger.info(e.getMessage());

                        try {
                            qualityReport = readEvaluateReport(scope, identifier, revision.toString(),
                                    transactionId);
                            break;
                        } catch (ResourceNotFoundException e1) {
                            logger.info(e1.getMessage());
                            Thread.sleep(idleSleepTime);
                            idleTime += idleSleepTime;
                        }
                    }
                }

                fiddlesticks(serviceMethod, idleTime, packageId, transactionId);
            } else {
                throw new UserErrorException(
                        "An EML packageId value could not be parsed from the file. Check that the file contains valid EML.");
            }

        } else {
            handleStatusCode(statusCode, entityString);
        }
    } finally {
        closeHttpClient(httpClient);
    }

    return qualityReport;
}

From source file:com.monarchapis.client.rest.BaseClient.java

@SuppressWarnings("deprecation")
public T setBody(File file, String contentType) throws RestException {
    this.body = new FileEntity(file, contentType);

    return me();/*from  w ww. jav  a 2 s  .  c  o  m*/
}

From source file:com.att.api.rest.RESTClient.java

/**
 * Sends an http POST request with the POST body set to the file.
 *
 * <p>/*w  ww  . j  a va  2s. c  o  m*/
 * <strong>NOTE</strong>: Any parameters set using
 * <code>addParameter()</code> or <code>setParameter()</code> will be
 * ignored.
 * </p>
 *
 * @param file file to use as POST body
 * @return api response
 * @throws RESTException if POST was unsuccessful
 */
public APIResponse httpPost(File file) throws RESTException {
    HttpResponse response = null;
    try {
        HttpClient httpClient = createClient();

        HttpPost httpPost = new HttpPost(url);
        addInternalHeaders(httpPost);

        String contentType = this.getMIMEType(file);

        httpPost.setEntity(new FileEntity(file, contentType));

        return buildResponse(httpClient.execute(httpPost));
    } catch (Exception e) {
        throw new RESTException(e);
    } finally {
        if (response != null) {
            this.releaseConnection(response);
        }
    }
}

From source file:org.rundeck.api.ApiCall.java

private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler,
        HttpEntityEnclosingRequestBase httpPost) {
    if (null != apiPath.getAccept()) {
        httpPost.setHeader("Accept", apiPath.getAccept());
    }//from  w  w  w  .j a  v  a 2  s.com
    // POST a multi-part request, with all attachments
    if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        ArrayList<File> tempfiles = new ArrayList<>();

        //attach streams
        for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) {
            if (client.isUseIntermediateStreamFile()) {
                //transfer to file
                File f = copyToTempfile(attachment.getValue());
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), f);
                tempfiles.add(f);
            } else {
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
            }
        }
        if (tempfiles.size() > 0) {
            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        }

        //attach files
        for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) {
            multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
        }

        httpPost.setEntity(multipartEntityBuilder.build());
    } else if (apiPath.getForm().size() > 0) {
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e);
        }
    } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) {
        if (client.isUseIntermediateStreamFile()) {
            ArrayList<File> tempfiles = new ArrayList<>();
            File f = copyToTempfile(apiPath.getContentStream());
            tempfiles.add(f);
            httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType())));

            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        } else {
            InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(),
                    ContentType.create(apiPath.getContentType()));
            httpPost.setEntity(entity);
        }
    } else if (apiPath.getContents() != null && apiPath.getContentType() != null) {
        ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(),
                ContentType.create(apiPath.getContentType()));

        httpPost.setEntity(bae);
    } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) {
        httpPost.setEntity(
                new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType())));
    } else if (apiPath.getXmlDocument() != null) {
        httpPost.setHeader("Content-Type", "application/xml");
        httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument())));
    } else if (apiPath.isEmptyContent()) {
        //empty content
    } else {
        throw new IllegalArgumentException("No Form or Multipart entity for POST content-body");
    }

    return execute(httpPost, handler);
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * @param clientName//from   w w  w .j av  a 2s  .c  o  m
 * @param url
 * @param fileName
 * @param filePath
 * @param username
 * @param password
 * @return
 */
private boolean put(String clientName, String url, String fileName, String filePath, String username,
        String password) {
    if ("".equals(clientName.trim()))
        return false;

    int status = 0;
    try {
        URL _url = createURLFromString(url);
        HttpPut method = new HttpPut(url + "/" + fileName);
        DefaultHttpClient client = getOrCreateHTTPclient(clientName, url);
        File file = new File(filePath);

        if (username != null && !"".equals(username.trim())) {
            BasicCredentialsProvider bcp = new BasicCredentialsProvider();
            bcp.setCredentials(new AuthScope(_url.getHost(), _url.getPort()),
                    new UsernamePasswordCredentials(username, password));
            client.setCredentialsProvider(bcp);
        }

        if (file == null || !file.exists()) {
            return false;
        }
        method.setEntity(new FileEntity(file, "binary/octet-stream"));
        HttpResponse res = client.execute(method);
        status = res.getStatusLine().getStatusCode();
    } catch (IOException e) {
        return false;
    }

    return (status == HttpStatus.SC_OK);
}