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:org.zaizi.alfresco.publishing.marklogic.MarkLogicChannelType.java

@Override
public void publish(final NodeRef nodeToPublish, final Map<QName, Serializable> channelProperties) {
    LOG.info("publish() invoked...");
    final ContentReader reader = contentService.getReader(nodeToPublish, ContentModel.PROP_CONTENT);
    if (reader.exists()) {
        File contentFile;//from ww  w.jav  a2  s. co  m
        boolean deleteContentFileOnCompletion = false;
        if (FileContentReader.class.isAssignableFrom(reader.getClass())) {
            // Grab the content straight from the content store if we can...
            contentFile = ((FileContentReader) reader).getFile();
        } else {
            // ...otherwise copy it to a temp file and use the copy...
            final File tempDir = TempFileProvider.getLongLifeTempDir("marklogic");
            contentFile = TempFileProvider.createTempFile("marklogic", "", tempDir);
            reader.getContent(contentFile);
            deleteContentFileOnCompletion = true;
        }

        HttpClient httpclient = new DefaultHttpClient();
        try {
            final String mimeType = reader.getMimetype();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Publishing node: " + nodeToPublish);
                LOG.debug("ContentFile_MIMETYPE: " + mimeType);
            }

            URI uriPut = publishingHelper.getPutURIFromNodeRefAndChannelProperties(nodeToPublish,
                    channelProperties);

            final HttpPut httpput = new HttpPut(uriPut);
            final FileEntity filenEntity = new FileEntity(contentFile, mimeType);
            httpput.setEntity(filenEntity);

            final HttpResponse response = httpclient.execute(httpput,
                    publishingHelper.getHttpContextFromChannelProperties(channelProperties));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Response Status: " + response.getStatusLine().getStatusCode() + " - Message: "
                        + response.getStatusLine().getReasonPhrase() + " - NodeRef: "
                        + nodeToPublish.toString());
            }
            if (response.getStatusLine().getStatusCode() != STATUS_DOCUMENT_INSERTED) {
                throw new AlfrescoRuntimeException(response.getStatusLine().getReasonPhrase());
            }
        } catch (IllegalStateException illegalEx) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", illegalEx);
            }
            throw new AlfrescoRuntimeException(illegalEx.getLocalizedMessage());
        } catch (IOException ioex) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", ioex);
            }
            throw new AlfrescoRuntimeException(ioex.getLocalizedMessage());
        } catch (URISyntaxException uriSynEx) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Exception in publish(): ", uriSynEx);
            }
            throw new AlfrescoRuntimeException(uriSynEx.getLocalizedMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
            if (deleteContentFileOnCompletion) {
                contentFile.delete();
            }
        }
    }
}

From source file:org.ocsinventoryng.android.actions.OCSProtocol.java

public String sendmethod(File pFile, String server, boolean gziped) throws OCSProtocolException {
    OCSLog ocslog = OCSLog.getInstance();
    OCSSettings ocssettings = OCSSettings.getInstance();
    ocslog.debug("Start send method");
    String retour;/*from w  w w . j a v a  2 s.  co  m*/

    HttpPost httppost;

    try {
        httppost = new HttpPost(server);
    } catch (IllegalArgumentException e) {
        ocslog.error(e.getMessage());
        throw new OCSProtocolException("Incorect serveur URL");
    }

    File fileToPost;
    if (gziped) {
        ocslog.debug("Start compression");
        fileToPost = ocsfile.getGzipedFile(pFile);
        if (fileToPost == null) {
            throw new OCSProtocolException("Error during temp file creation");
        }
        ocslog.debug("Compression done");
    } else {
        fileToPost = pFile;
    }

    FileEntity fileEntity = new FileEntity(fileToPost, "text/plain; charset=\"UTF-8\"");
    httppost.setEntity(fileEntity);
    httppost.setHeader("User-Agent", http_agent);
    if (gziped) {
        httppost.setHeader("Content-Encoding", "gzip");
    }

    DefaultHttpClient httpClient = getNewHttpClient(OCSSettings.getInstance().isSSLStrict());

    if (ocssettings.isProxy()) {
        ocslog.debug("Use proxy : " + ocssettings.getProxyAdr());
        HttpHost proxy = new HttpHost(ocssettings.getProxyAdr(), ocssettings.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    if (ocssettings.isAuth()) {
        ocslog.debug("Use AUTH : " + ocssettings.getLogin() + "/*****");
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(ocssettings.getLogin(),
                ocssettings.getPasswd());
        ocslog.debug(creds.toString());
        httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    }

    ocslog.debug("Call : " + server);
    HttpResponse localHttpResponse;
    try {
        localHttpResponse = httpClient.execute(httppost);
        ocslog.debug("Message sent");
    } catch (ClientProtocolException e) {
        ocslog.error("ClientProtocolException" + e.getMessage());
        throw new OCSProtocolException(e.getMessage());
    } catch (IOException e) {
        String msg = appCtx.getString(R.string.err_cant_connect) + " " + e.getMessage();
        ocslog.error(msg);
        throw new OCSProtocolException(msg);
    }

    try {
        int httpCode = localHttpResponse.getStatusLine().getStatusCode();
        ocslog.debug("Response status code : " + String.valueOf(httpCode));
        if (httpCode == 200) {
            if (gziped) {
                InputStream is = localHttpResponse.getEntity().getContent();
                GZIPInputStream gzis = new GZIPInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buff = new byte[128];
                int n;
                while ((n = gzis.read(buff, 0, buff.length)) > 0) {
                    baos.write(buff, 0, n);
                }
                retour = baos.toString();
            } else {
                retour = EntityUtils.toString(localHttpResponse.getEntity());
            }
        } else if (httpCode == 400) {
            throw new OCSProtocolException("Error http 400 may be wrong agent version");
        } else {
            ocslog.error("***Server communication error: ");
            throw new OCSProtocolException("Http communication error code " + String.valueOf(httpCode));
        }
        ocslog.debug("Finnish send method");
    } catch (IOException localIOException) {
        String msg = localIOException.getMessage();
        ocslog.error(msg);
        throw new OCSProtocolException(msg);
    }
    return retour;
}

From source file:code.google.restclient.client.HitterClient.java

/**
 * Method to get file entity from file object
 *//* w  ww . ja  va 2  s .  c o m*/
private FileEntity hit(File body) throws Exception {
    FileEntity fileEntity = new FileEntity(body, ""); // second argument is contentType e.g. "text/plain; charset=\"UTF-8\"");
    return fileEntity;
}

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

private void doDeposit(File file) throws Exception {

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

    //FileInputStream fis = new FileInputStream(file);
    //post.setEntity(new InputStreamEntity(fis, file.length()));
    post.setEntity(new FileEntity(file, "application/xml"));

    HttpResponse response = client.execute(post);

    int code = response.getStatusLine().getStatusCode();
    if (code >= 200 && code <= 202) {
        response.getAllHeaders();/* w ww.j a v a  2s. c o m*/
        HttpEntity responseEntity = response.getEntity();
        InputStream content = responseEntity.getContent();
        try {
            IOUtils.toByteArray(content);
        } finally {
            content.close();
        }
    } else {
        throw new RuntimeException("Unexpected error code " + code);
    }
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@Test
@SuppressWarnings("deprecation")
public void testFileEntity() throws Exception {
    File file = new File("src/test/resources/README.txt");
    FileEntity entity = new FileEntity(file, "text/plain; charset=\"UTF-8\"");
    System.out.println(entity.getContentLength() + "");
    System.out.println(entity.getContentType() + "");
    String content = parseEntity(entity);
    System.out.println(content);/*ww w. j a va2 s .c  o m*/
}

From source file:nl.gridline.zieook.workflow.rest.CollectionImportCompleteTest.java

@Ignore
private int collectionUpload(String url, File file) {
    // upload binary collection data

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpEntity entity = new FileEntity(file, "binary/octet-stream");

    HttpPut post = new HttpPut(url);
    post.setEntity(entity);//from ww  w .java 2 s. co  m
    try {
        HttpResponse response = httpclient.execute(post);
        return response.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        LOG.error("upload failed", e);
        fail("upload failed");
    } catch (IOException e) {
        LOG.error("upload failed", e);
        fail("upload failed");
    }
    return 500;
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@Test
public void testEntityChunk() throws Exception {
    File file = new File("src/test/resources/README.txt");
    @SuppressWarnings("deprecation")
    FileEntity entity = new FileEntity(file, "text/plain; charset=\"UTF-8\"");
    entity.setChunked(true);/*from  ww w .j av  a  2s.  com*/
    System.out.println(entity.isChunked() + "");
}

From source file:org.jvoicexml.documentserver.schemestrategy.HttpSchemeStrategy.java

/**
 * Attach the files given in the parameters.
 * /* w  w  w.  j  av a  2 s  . com*/
 * @param request
 *            the current request
 * @param parameters
 *            the parameters
 * @since 0.7.3
 */
private void attachFiles(final HttpUriRequest request, final Collection<KeyValuePair> parameters) {
    if (!(request instanceof HttpPost)) {
        return;
    }
    final HttpPost post = (HttpPost) request;
    for (KeyValuePair current : parameters) {
        final Object value = current.getValue();
        if (value instanceof File) {
            final File file = (File) value;
            final FileEntity fileEntity = new FileEntity(file, ContentType.create("binary/octet-stream"));
            post.setEntity(fileEntity);
        }
    }
}

From source file:org.semantictools.frame.api.OntologyManager.java

private void uploadFile(File file, String contentType) throws ClientProtocolException, IOException {
    System.out.println("Uploading... " + file);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(ontologyServiceURI);

    FileEntity fileEntity = new FileEntity(file, contentType);
    post.setEntity(fileEntity);/* w  w w  .  jav a 2s. c om*/

    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    switch (status) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:

        break;

    default:
        System.out.println(" ERROR: " + status);

    }
}