Search in sources :

Example 1 with FileEntity

use of org.apache.http.entity.FileEntity in project RoboZombie by sahan.

the class Entities method resolve.

/**
	  * <p>Discovers which implementation of {@link HttpEntity} is suitable for wrapping the given object. 
	  * This discovery proceeds in the following order by checking the runtime-type of the object:</p> 
	  *
	  * <ol>
	  * 	<li>org.apache.http.{@link HttpEntity} --&gt; returned as-is.</li> 
	  * 	<li>{@code byte[]}, {@link Byte}[] --&gt; {@link ByteArrayEntity}</li> 
	  *  	<li>java.io.{@link File} --&gt; {@link FileEntity}</li>
	  * 	<li>java.io.{@link InputStream} --&gt; {@link BufferedHttpEntity}</li>
	  * 	<li>{@link CharSequence} --&gt; {@link StringEntity}</li>
	  * 	<li>java.io.{@link Serializable} --&gt; {@link SerializableEntity} (with an internal buffer)</li>
	  * </ol>
	  *
	  * @param genericEntity
	  * 			a generic reference to an object whose concrete {@link HttpEntity} is to be resolved 
	  * <br><br>
	  * @return the resolved concrete {@link HttpEntity} implementation
	  * <br><br>
	  * @throws NullPointerException
	  * 			if the supplied generic type was {@code null}
	  * <br><br>
	  * @throws EntityResolutionFailedException
	  * 			if the given generic instance failed to be translated to an {@link HttpEntity} 
	  * <br><br>
	  * @since 1.3.0
	  */
public static final HttpEntity resolve(Object genericEntity) {
    assertNotNull(genericEntity);
    try {
        if (genericEntity instanceof HttpEntity) {
            return (HttpEntity) genericEntity;
        } else if (byte[].class.isAssignableFrom(genericEntity.getClass())) {
            return new ByteArrayEntity((byte[]) genericEntity);
        } else if (Byte[].class.isAssignableFrom(genericEntity.getClass())) {
            Byte[] wrapperBytes = (Byte[]) genericEntity;
            byte[] primitiveBytes = new byte[wrapperBytes.length];
            for (int i = 0; i < wrapperBytes.length; i++) {
                primitiveBytes[i] = wrapperBytes[i].byteValue();
            }
            return new ByteArrayEntity(primitiveBytes);
        } else if (genericEntity instanceof File) {
            return new FileEntity((File) genericEntity, null);
        } else if (genericEntity instanceof InputStream) {
            BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
            basicHttpEntity.setContent((InputStream) genericEntity);
            return new BufferedHttpEntity(basicHttpEntity);
        } else if (genericEntity instanceof CharSequence) {
            return new StringEntity(((CharSequence) genericEntity).toString());
        } else if (genericEntity instanceof Serializable) {
            return new SerializableEntity((Serializable) genericEntity, true);
        } else {
            throw new EntityResolutionFailedException(genericEntity);
        }
    } catch (Exception e) {
        throw (e instanceof EntityResolutionFailedException) ? (EntityResolutionFailedException) e : new EntityResolutionFailedException(genericEntity, e);
    }
}
Also used : FileEntity(org.apache.http.entity.FileEntity) Serializable(java.io.Serializable) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) InputStream(java.io.InputStream) SerializableEntity(org.apache.http.entity.SerializableEntity) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) File(java.io.File)

Example 2 with FileEntity

use of org.apache.http.entity.FileEntity in project RoboZombie by sahan.

the class RequestParamEndpointTest method testFileEntity.

/**
	 * <p>Test for a {@link Request} with a {@link File} entity.</p>
	 * 
	 * @since 1.3.0
	 */
@Test
public final void testFileEntity() throws ParseException, IOException, URISyntaxException {
    Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
    String subpath = "/fileentity";
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    File file = new File(classLoader.getResource("LICENSE.txt").toURI());
    FileEntity fe = new FileEntity(file, null);
    stubFor(put(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));
    requestEndpoint.fileEntity(file);
    verify(putRequestedFor(urlEqualTo(subpath)).withRequestBody(equalTo(EntityUtils.toString(fe))));
}
Also used : FileEntity(org.apache.http.entity.FileEntity) File(java.io.File) Test(org.junit.Test)

Example 3 with FileEntity

use of org.apache.http.entity.FileEntity in project appsly-android-rest by 47deg.

the class DefaultRestClientImpl method postFile.

@Override
public <T> void postFile(String url, File file, Callback<T> delegate) {
    prepareRequest(delegate);
    client.post(delegate.getContext(), url, delegate.getAdditionalHeaders(), new FileEntity(file, delegate.getRequestContentType()), delegate.getRequestContentType(), delegate);
}
Also used : FileEntity(org.apache.http.entity.FileEntity)

Example 4 with FileEntity

use of org.apache.http.entity.FileEntity in project ats-framework by Axway.

the class HttpClient method performUploadFile.

@Override
protected void performUploadFile(String localFile, String remoteDir, String remoteFile) throws FileTransferException {
    checkClientInitialized();
    final String uploadUrl = constructUploadUrl(remoteDir, remoteFile);
    log.info("Uploading " + uploadUrl);
    HttpEntityEnclosingRequestBase uploadMethod;
    Object uploadMethodObject = customProperties.get(HTTP_HTTPS_UPLOAD_METHOD);
    if (uploadMethodObject == null || !uploadMethodObject.toString().equals(HTTP_HTTPS_UPLOAD_METHOD__POST)) {
        uploadMethod = new HttpPut(uploadUrl);
    } else {
        uploadMethod = new HttpPost(uploadUrl);
    }
    String contentType = DEFAULT_HTTP_HTTPS_UPLOAD_CONTENT_TYPE;
    Object contentTypeObject = customProperties.get(HTTP_HTTPS_UPLOAD_CONTENT_TYPE);
    if (contentTypeObject != null) {
        contentType = contentTypeObject.toString();
    }
    FileEntity fileUploadEntity = new FileEntity(new File(localFile), ContentType.parse(contentType));
    uploadMethod.setEntity(fileUploadEntity);
    HttpResponse response = null;
    try {
        // add headers specified by the user
        addRequestHeaders(uploadMethod);
        // upload the file
        response = httpClient.execute(uploadMethod, httpContext);
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode < 200 || responseCode > 206) {
            // 204 No Content - there was a file with same name on same location, we replaced it
            throw new FileTransferException("Uploading '" + uploadUrl + "' returned '" + response.getStatusLine() + "'");
        }
    } catch (ClientProtocolException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } finally {
        // the UPLOAD returns response body on error
        if (response != null && response.getEntity() != null) {
            HttpEntity responseEntity = response.getEntity();
            // the underlying stream has been closed
            try {
                EntityUtils.consume(responseEntity);
            } catch (IOException e) {
            // we tried our best to release the resources
            }
        }
    }
    log.info("Successfully uploaded '" + localFile + "' to '" + remoteDir + remoteFile + "', host " + this.hostname);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) FileEntity(org.apache.http.entity.FileEntity) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) File(java.io.File)

Example 5 with FileEntity

use of org.apache.http.entity.FileEntity in project asterixdb by apache.

the class HyracksConnection method deployBinary.

@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<>();
    if (jars != null && !jars.isEmpty()) {
        CloseableHttpClient hc = new DefaultHttpClient();
        try {
            /** 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);
                response.getEntity().consumeContent();
                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));
            }
        } finally {
            hc.close();
        }
    }
    /** deploy the URLs to the CC and NCs */
    hci.deployBinary(binaryURLs, deploymentId);
    return deploymentId;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) DeploymentId(org.apache.hyracks.api.deployment.DeploymentId) FileEntity(org.apache.http.entity.FileEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpPut(org.apache.http.client.methods.HttpPut) File(java.io.File)

Aggregations

FileEntity (org.apache.http.entity.FileEntity)12 File (java.io.File)11 HttpEntity (org.apache.http.HttpEntity)7 StringEntity (org.apache.http.entity.StringEntity)4 InputStream (java.io.InputStream)3 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 Serializable (java.io.Serializable)2 Charset (java.nio.charset.Charset)2 ArrayList (java.util.ArrayList)2 HttpResponse (org.apache.http.HttpResponse)2 HttpPut (org.apache.http.client.methods.HttpPut)2 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)2 HTTPArgument (org.apache.jmeter.protocol.http.util.HTTPArgument)2 HTTPFileArg (org.apache.jmeter.protocol.http.util.HTTPFileArg)2 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)2 FileTransferException (com.axway.ats.common.filetransfer.FileTransferException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URL (java.net.URL)1