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.hp.mqm.clt.RestClientTest.java

@Test
public void testPostTestResult_skipErrors()
        throws IOException, URISyntaxException, InterruptedException, ValidationException {
    RestClient client = new RestClient(testClientSettings);
    long timestamp = System.currentTimeMillis();

    // try content that fails unless skip-errors is specified
    String testResultXmlInvalidRelease = ResourceUtils.readContent("TestResultWithRelease.xml")
            .replaceAll("%%%RELEASE_REF%%%", String.valueOf(Integer.MAX_VALUE))
            .replaceAll("%%%TIMESTAMP%%%", String.valueOf(timestamp));
    final File testResultInvalidRelease = temporaryFolder.newFile();
    FileUtils.write(testResultInvalidRelease, testResultXmlInvalidRelease);
    try {//from  w w  w .j  a  v a2s  .  c  o m
        long id = client.postTestResult(new FileEntity(testResultInvalidRelease, ContentType.APPLICATION_XML));
        assertPublishResult(id, "failed");
    } finally {
        client.release();
    }

    PagedList<TestRun> pagedList = testSupportClient.queryTestRuns("testTwo" + timestamp, 0, 50);
    Assert.assertEquals(0, pagedList.getItems().size());

    // push the same content, but with skip-errors set to true
    testClientSettings.setSkipErrors(true);
    try {
        long id = client.postTestResult(new FileEntity(testResultInvalidRelease, ContentType.APPLICATION_XML));
        assertPublishResult(id, "warning");
    } finally {
        client.release();
    }

    pagedList = testSupportClient.queryTestRuns("testTwo" + timestamp, 0, 50);
    Assert.assertEquals(1, pagedList.getItems().size());
    Assert.assertEquals("testTwo" + timestamp, pagedList.getItems().get(0).getName());
}

From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java

private void uploadConfiguration() throws IOException {
    System.out.print(ImplMessages.getMessage("PROVISIONER_UPLOADING_CONFIG_MSG"));
    // String url = "https://"+hostname+":"+6143+"/geoevent/admin/configuration/install/.json";
    String url = "https://" + hostName + ":" + 6143 + "/geoevent/admin/configuration/.json";

    File configAsFile = new File(configFile);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory()).build();
    FileEntity file = new FileEntity(configAsFile, ContentType.APPLICATION_XML);
    HttpUriRequest post = RequestBuilder.put().setUri(url).addHeader("GeoEventAuthorization", token)
            .addHeader("referer", referer).setEntity(file).build();

    HttpResponse response = httpClient.execute(post);
    HttpEntity entity = response.getEntity();
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unused")
    JsonNode jsonResponse = mapper.readTree(entity.getContent());
    sleep(10 * 1000);//  w w w  . j a  v  a2s.  c om
    System.out.println(ImplMessages.getMessage("DONE"));
}

From source file:es.eucm.eadventure.tracking.prv.service.TrackingPoster.java

public boolean sendSnapshot(File file) {
    if (baseURL == null)
        return false;
    if (snapshotsPath == null)
        return false;
    boolean sent = false;
    try {//from   w  w w.ja v  a  2s .c  o m
        HttpClient httpclient = new DefaultHttpClient();
        String url = baseURL + (baseURL.endsWith("/") ? "" : "/") + snapshotsPath;

        HttpPost httpput = new HttpPost(url);
        FileEntity myEntity = new FileEntity(file, "image/jpeg");
        httpput.setEntity(myEntity);
        HttpResponse response;

        response = httpclient.execute(httpput);
        if (response != null && Integer.toString(response.getStatusLine().getStatusCode()).startsWith("2")) {
            sent = true;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sent;

}

From source file:com.aretha.net.HttpConnectionHelper.java

/**
 * Obtain a {@link HttpPost} request//from  w  ww  .  j  ava 2 s  .com
 * 
 * @param url
 * @param file
 *            File to upload
 * @return
 */
public HttpPost obtainHttpPostRequest(String url, File file) {
    if (null == file || null == url) {
        throw new IllegalArgumentException("url and file can not be null");
    }

    HttpPost post = new HttpPost(url);
    FileEntity entity = new FileEntity(file, "binary/octet-stream");
    post.setEntity(entity);
    return post;
}

From source file:de.fhg.iais.cortex.server.client.RestIngestManagedConnections.java

/**
 * send the request and return the result as enumeration SendRequestResult
 * /*from w ww  .jav  a 2 s .c  om*/
 * @param requestParam not null
 * @param requestEntity may be null
 * @param mimeType may be null
 * @return the SendRequestResult, not null
 */
private SendRequestResult send(String path, String requestParam, Object requestEntity, String mimeType) {
    IngestServerState ingestServerState = getHopeFullyAccessableNotOverloadedIngestServer();
    SendRequestResult result = SendRequestResult.SUCCESS;
    String message = null;
    int retryCounter;
    for (retryCounter = 0; retryCounter < RETRY_COUNTER; retryCounter++) {
        HttpPut put = null;
        try {
            StringBuilder uri = new StringBuilder();
            uri.append(ingestServerState.getUrl()).append(PATH_INGEST).append(this.revisionPath);
            if (path != null) {
                uri.append("/").append(path);
            }
            if (requestParam != null) {
                uri.append(requestParam);
            }
            put = new HttpPut(uri.toString());
            put.addHeader(HttpHeaders.ACCEPT, MediaType.WILDCARD);
            HttpEntity httpEntity = null;
            if (requestEntity instanceof File) {
                httpEntity = new FileEntity((File) requestEntity, mimeType);
            } else if (requestEntity instanceof String) {
                httpEntity = new StringEntity((String) requestEntity, mimeType, Charsets.UTF_8.name());
            }
            if (httpEntity != null) {
                put.setEntity(httpEntity);
            }

            HttpResponse response = RestClientManager.getInstance().setProxy(this.proxy).getHttpClient()
                    .execute(put);
            String responseEntity = getResponseEntityAsString(response);
            Pair<SendRequestResult, String> resultAndMessage = prepareStatusMessage(null, requestEntity,
                    responseEntity, response.getStatusLine());
            result = resultAndMessage.getFirst();
            message = resultAndMessage.getSecond();
            if ((message == null) || (result == SendRequestResult.SUCCESS)
                    || (result == SendRequestResult.INGEST_SERVER_ERROR)) {
                break; // successful put, or retry is nonsense
            }
        } catch (Exception e) {
            Pair<SendRequestResult, String> resultAndMessage = prepareStatusMessage(null, requestEntity, null,
                    null);
            result = resultAndMessage.getFirst();
            message = resultAndMessage.getSecond();
            if (put != null) {
                put.abort();
            }
            if ((result == SendRequestResult.SUCCESS) || (result == SendRequestResult.INGEST_SERVER_ERROR)) {
                break; // retry is nonsense
            }
        }
    }
    if (message != null) {
        if (result == SendRequestResult.INGEST_SERVER_ERROR) {
            LOG.error(makeBasicMessage(null, requestEntity, null, "FAILED due to ingest server errors.",
                    message));
        } else if (result == SendRequestResult.COMMUNICATION_ERROR) {
            ingestServerState.failure();
            LOG.warn(makeBasicMessage(null, requestEntity, null, "FAILED due to communication problems of "
                    + ingestServerState + ". Trying another ingest server", null));
        } else {
            LOG.error("FAILED due to an internal inconsistency.", message);
            result = SendRequestResult.INGEST_SERVER_ERROR; // force an error entry
        }
        return result;
    } else {
        if (retryCounter > 0) {
            String finalMessage = makeBasicMessage(null, requestEntity, null,
                    "succeeded after " + retryCounter + " retries", null);
            LOG.warn(finalMessage);
        }
        ingestServerState.success();
        return SendRequestResult.SUCCESS;
    }
}

From source file:org.dataconservancy.dcs.integration.main.IngestTest.java

private int doDeposit(File file) throws Exception {

    HttpPost post = new HttpPost(sipPostUrl);
    post.setHeader(HttpHeaderUtil.CONTENT_TYPE, "application/xml");
    post.setHeader("X-Packaging", "http://dataconservancy.org/schemas/dcp/1.0");

    post.setEntity(new FileEntity(file, "application/xml"));

    HttpResponse response = client.execute(post);

    int code = response.getStatusLine().getStatusCode();
    if (code >= 200 && code <= 202) {
        response.getAllHeaders();//  www. j av a2 s . c  o  m
        HttpEntity responseEntity = response.getEntity();
        InputStream content = responseEntity.getContent();
        try {
            IOUtils.toByteArray(content);
        } finally {
            content.close();
        }
    }
    return code;
}

From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCallerUtils.java

/**
 * Constructs octet-stream entity based upon the specified value or the file and its mimetype (ie. request
 * parameter).//from w  ww .j  a  v a  2s .co  m
 * 
 * @param requestParam
 *            request parameter
 * @return request octet-stream entity for the service
 */
private static HttpEntity constructOctetStreamEntity(ExecutionBodyParam requestParam) {
    if (requestParam == null) {
        return null;
    }
    if (requestParam.getValue() != null) {
        return new StringEntity(requestParam.getValue(), TEXTPLAIN);
    }
    if (requestParam.getFileValue() != null) {
        try {
            ContentType contentType = ContentType.create(requestParam.getFileValue().getMimetype());
            return new FileEntity(requestParam.getFileValue().getFile(), contentType);
        } catch (IllegalArgumentException e) {
            return new FileEntity(requestParam.getFileValue().getFile());
        }
    }
    return null;
}

From source file:com.autburst.picture.server.HttpRequest.java

public void post(String url, File file) throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    try {/*from www  . j  a  v a2  s.c  o  m*/

        httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 sec.
        HttpPost post = new HttpPost(url);

        //         Multi mpEntity = new MultipartEntity();
        //          ContentBody cbFile = new FileBody(file, "image/jpeg");
        //          mpEntity.addPart("userfile", cbFile);

        FileEntity entity;

        // entity = new FileEntity(file, "binary/octet-stream");
        entity = new FileEntity(file, "image/jpeg");
        //entity.setChunked(true);
        post.setEntity(entity);
        //post.setHeader("Content-type", "image/jpeg");
        // Send any XML file as the body of the POST request
        //           File f = new File("students.xml");
        //           System.out.println("File Length = " + f.length());

        //           post.setBody(new FileInputStream(file));
        ////           c
        ////               "image/jpeg; charset=ISO-8859-1");
        //           post.setHeader("Content-type", "image/jpeg");
        post.addHeader("filename", file.getName());

        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
            Log.e(TAG, "--------Error--------Response Status linecode:" + response.getStatusLine());
            throw new Exception("--------Error--------Response Status linecode:" + response.getStatusLine());
        }
        // else {
        // // Here every thing is fine.
        // }
        // HttpEntity resEntity = response.getEntity();
        // if (resEntity == null) {
        // Log.e(TAG, "---------Error No Response !!!-----");
        // }
    } catch (Exception ex) {
        Log.e(TAG, "---------Error-----" + ex.getMessage());
        throw new Exception(ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.graphwalker.restful.RestTest.java

@Override
public void e_Load() {
    HttpPost request = new HttpPost("http://localhost:9191/graphwalker/load");
    FileEntity fileEntity = new FileEntity(ResourceUtils.getResourceAsFile("gw3/UC01.json"),
            ContentType.TEXT_PLAIN);//from   w  w w .j  a v a2s.c o  m
    request.setEntity(fileEntity);
    response = httpExecute(request);
}