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:v7cr.V7CR.java

BSONBackedObject storeFile(File file, String fileName, String mimeType) throws IOException {
    HttpClient http = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://0.0.0.0:8088/upload/v7cr");
    put.setEntity(new FileEntity(file, mimeType));
    HttpResponse response = http.execute(put);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("failed to save " + fileName + ": " + response.getStatusLine());
    }//  w  w  w .ja  v a2 s . co m

    String sha = IOUtils.toString(response.getEntity().getContent());
    BSONObject r = new BasicBSONObject("sha", sha);
    r.put("filename", fileName);
    r.put("contentType", mimeType);
    r.put("length", file.length());
    return BSONBackedObjectLoader.wrap(r, null);
}

From source file:com.hpe.application.automation.tools.pc.MockPcRestProxy.java

@Override
protected HttpResponse executeRequest(HttpRequestBase request)
        throws PcException, ClientProtocolException, IOException {
    HttpResponse response = null;//from w  w  w.j  a v  a2 s .c o  m
    String requestUrl = request.getURI().toString();
    if (requestUrl
            .equals(String.format(AUTHENTICATION_LOGIN_URL, PcTestBase.WEB_PROTOCOL, PcTestBase.PC_SERVER_NAME))
            || requestUrl.equals(String.format(AUTHENTICATION_LOGOUT_URL, PcTestBase.WEB_PROTOCOL,
                    PcTestBase.PC_SERVER_NAME))
            || requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s", RUNS_RESOURCE_NAME,
                    PcTestBase.RUN_ID, PcTestBase.STOP_MODE))) {
        response = getOkResponse();
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s", RUNS_RESOURCE_NAME)) || requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", RUNS_RESOURCE_NAME, PcTestBase.RUN_ID))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.runResponseEntity));
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s", TESTS_RESOURCE_NAME)) || requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", TESTS_RESOURCE_NAME, PcTestBase.TEST_ID))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.testResponseEntity));
    } else if (requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", RUNS_RESOURCE_NAME, PcTestBase.RUN_ID_WAIT))) {
        response = getOkResponse();
        response.setEntity(
                new StringEntity(PcTestBase.runResponseEntity.replace("*", runState.next().value())));
        if (!runState.hasNext())
            runState = initializeRunStateIterator();
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s", RUNS_RESOURCE_NAME,
            PcTestBase.RUN_ID, RESULTS_RESOURCE_NAME))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.runResultsEntity));
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s/%s/data", RUNS_RESOURCE_NAME,
            PcTestBase.RUN_ID, RESULTS_RESOURCE_NAME, PcTestBase.REPORT_ID))) {
        response = getOkResponse();
        response.setEntity(
                new FileEntity(new File(getClass().getResource(PcBuilder.pcReportArchiveName).getPath()),
                        ContentType.DEFAULT_BINARY));
    }
    if (response == null)
        throw new PcException(
                String.format("%s %s is not recognized by PC Rest Proxy", request.getMethod(), requestUrl));
    return response;
}

From source file:edu.uci.ics.hyracks.api.client.HyracksConnection.java

@Override
public DeploymentId deployBinary(List<String> jars) throws Exception {
    /** generate a deployment id */
    DeploymentId deploymentId = new DeploymentId(UUID.randomUUID().toString());
    List<URL> binaryURLs = new ArrayList<URL>();
    if (jars != null && jars.size() > 0) {
        HttpClient hc = new DefaultHttpClient();
        /** upload jars through a http client one-by-one to the CC server */
        for (String jar : jars) {
            int slashIndex = jar.lastIndexOf('/');
            String fileName = jar.substring(slashIndex + 1);
            String url = "http://" + ccHost + ":" + ccInfo.getWebPort() + "/applications/"
                    + deploymentId.toString() + "&" + fileName;
            HttpPut put = new HttpPut(url);
            put.setEntity(new FileEntity(new File(jar), "application/octet-stream"));
            HttpResponse response = hc.execute(put);
            if (response != null) {
                response.getEntity().consumeContent();
            }/*w ww .j a v a2 s .c  o  m*/
            if (response.getStatusLine().getStatusCode() != 200) {
                hci.unDeployBinary(deploymentId);
                throw new HyracksException(response.getStatusLine().toString());
            }
            /** add the uploaded URL address into the URLs of jars to be deployed at NCs */
            binaryURLs.add(new URL(url));
        }
    }
    /** deploy the URLs to the CC and NCs */
    hci.deployBinary(binaryURLs, deploymentId);
    return deploymentId;
}

From source file:com.anrisoftware.simplerest.owncloudocs.OwncloudOcsUploadFile.java

private void sendRequest() throws SimpleRestException {
    URI requestUri = getRequestURI();
    SimplePutWorker requestWorker = workerFactory.create(this, requestUri, getAccount(), httpClient,
            nopParseResponse, nopParseResponse);
    requestWorker.addHeader("OC-Total-Length", Long.toString(FileUtils.sizeOf(file)));
    if (requiredEtag != null) {
        requestWorker.addHeader("If-Match", requiredEtag);
    }/*from   w  w w  .j  a  v  a  2  s .  c o m*/
    HttpEntity entity = new FileEntity(file, contentType);
    requestWorker.sendData(entity);
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

public void addFilePostParam(String path) {
    fileEntity = new FileEntity(new File(path), URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM + HTTP.UTF_8);
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

/**
 * Uploads a {@code File} with PRIVATE read access.
 *
 * @param uri upload {@link URI}//from  w ww .  j  a  v  a2 s  .c o  m
 * @param contentTypeString content type
 * @param contentFile the file to upload
 * @throws IOException
 */
public static void uploadPrivateContent(final URI uri, final String contentTypeString, final File contentFile)
        throws IOException {

    LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
            new Object[] { uri, contentTypeString, contentFile });

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
        throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s",
                statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
            new Object[] { uri, contentTypeString, contentFile });
}

From source file:com.ibm.watson.developer_cloud.alchemy.v1.AlchemyVision.java

/**
 * Execute the request and return the POJO that represent the response.
 *
 * @param <T>        The POJO that represents the response object
 * @param params     the request parameters
 * @param operation  the alchemy operation
 * @param returnType the POJO class to be parsed from the response
 * @return the POJO object that represent the response
 *//*  w  w w .  java2  s .  co  m*/
private <T> T executeRequest(Map<String, Object> params, AlchemyAPI operation, Class<T> returnType) {
    String inputType = getInputFormat(params, "image", "url");
    String path = AlchemyEndPoints.getPath(operation, inputType);

    Request request = Request.Post(path);
    if (inputType == IMAGE) {
        if (params.get(IMAGE) instanceof String) {
            params.put(IMAGE_POST_MODE, NOT_RAW);
        } else {
            params.put(IMAGE_POST_MODE, RAW);
            File image = (File) params.get(IMAGE);
            if (!image.exists()) {
                throw new IllegalArgumentException("The file: " + image.getAbsolutePath() + " does not exist.");
            } else {
                // if image is a file add it as file entity and remove it from the parameters
                request.withEntity(
                        new FileEntity((File) params.get(IMAGE), MediaType.APPLICATION_OCTET_STREAM));
                params.remove("image");
            }
        }
    }

    // set json as default output mode
    params.put(OUTPUT_MODE, "json");

    // add all the parameters into the request as form-url-encoded parameters
    for (String param : params.keySet()) {
        if (inputType.equals("image")) {
            request.withQuery(param, params.get(param));
        } else {
            request.withForm(param, params.get(param));
        }
    }

    HttpRequestBase requestBase = request.build();
    try {
        HttpResponse response = execute(requestBase);
        return ResponseUtil.getObject(response, returnType);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.http.apachehc.ApacheHCUtils.java

public void addEntityForContent(HttpEntityEnclosingRequest apacheRequest, Payload payload) {
    payload = payload instanceof DelegatingPayload ? DelegatingPayload.class.cast(payload).getDelegate()
            : payload;/*from ww w .jav a  2  s  . c  o  m*/
    if (payload instanceof StringPayload) {
        StringEntity nStringEntity = null;
        try {
            nStringEntity = new StringEntity((String) payload.getRawContent());
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("Encoding not supported", e);
        }
        nStringEntity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(nStringEntity);
    } else if (payload instanceof FilePayload) {
        apacheRequest.setEntity(
                new FileEntity((File) payload.getRawContent(), payload.getContentMetadata().getContentType()));
    } else if (payload instanceof ByteArrayPayload) {
        ByteArrayEntity Entity = new ByteArrayEntity((byte[]) payload.getRawContent());
        Entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(Entity);
    } else {
        InputStream inputStream = payload.getInput();
        if (payload.getContentMetadata().getContentLength() == null)
            throw new IllegalArgumentException("you must specify size when content is an InputStream");
        InputStreamEntity entity = new InputStreamEntity(inputStream,
                payload.getContentMetadata().getContentLength());
        entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(entity);
    }

    // TODO Reproducing old behaviour exactly; ignoring Content-Type, Content-Length and Content-MD5
    Set<String> desiredHeaders = ImmutableSet.of("Content-Disposition", "Content-Encoding", "Content-Language",
            "Expires");
    MutableContentMetadata md = payload.getContentMetadata();
    for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {
        if (desiredHeaders.contains(entry.getKey())) {
            apacheRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }

    assert apacheRequest.getEntity() != null;
}