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

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

Introduction

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

Prototype

public ByteArrayEntity(byte[] bArr) 

Source Link

Usage

From source file:com.leprechaun.solveig.http.RequestExecutor.java

public static ResponseEntity intermediateExcutor(String host, String port, String dbName, String username,
        String password, String query) throws Exception {

    ResponseEntity responseEntity = new ResponseEntity();

    //INSERT/*from  ww w .  jav  a  2s .  c om*/

    if (query.toLowerCase().contains("insert")) {

        //query.replaceFirst("insert", "");

        query = query.substring(7);

        HttpClient client = new DefaultHttpClient();
        String url = "http://" + host + ":" + port + "/write?";

        if (!dbName.isEmpty() || dbName == null) {
            url += "db=" + dbName + "&";
        }

        if (!username.isEmpty() || username == null) {
            url += "u=" + username + "&";
        }
        if (!password.isEmpty() || password == null) {
            url += "u=" + password + "&";
        }

        if (url.toCharArray()[url.toCharArray().length - 1] == '&') {
            url = url.substring(0, url.toCharArray().length - 1);
        }

        //String body = requestFormatter(query);
        HttpPost post = new HttpPost(url);

        System.out.println(query);

        HttpEntity httpEntity = new ByteArrayEntity(query.getBytes("UTF-8"));
        post.setEntity(httpEntity);

        try {
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            /*String responseString = EntityUtils.toString(entity, "UTF-8");
            System.out.println(responseString);
                    
            responseEntity.setCode(response.getStatusLine().toString());
            responseEntity.setBody(responseString);*/
            responseEntity.setCode("OK");
            responseEntity.setBody("");
        } catch (IOException e) {
            System.out.println(e.getMessage());

            responseEntity.setCode("ERROR");
            responseEntity.setBody(e.getMessage());
        }

    } //SELECT
    else {

        HttpClient client = new DefaultHttpClient();

        String url = "http://" + host + ":" + port + "/query?";

        if (!dbName.isEmpty() || dbName == null) {
            url += "db=" + dbName + "&";
        }

        if (!username.isEmpty() || username == null) {
            url += "u=" + username + "&";
        }
        if (!password.isEmpty() || password == null) {
            url += "u=" + password + "&";
        }

        url += "q=" + requestFormatter(query);

        HttpGet get = new HttpGet(url);

        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");
            System.out.println(responseString);

            responseEntity.setCode(response.getStatusLine().toString());
            responseEntity.setBody(responseString);
        } catch (IOException e) {
            System.out.println(e.getMessage());

            responseEntity.setCode("ERROR");
            responseEntity.setBody(e.getMessage());
        }
    }

    return responseEntity;
}

From source file:com.lonepulse.robozombie.util.Entities.java

/**
 * <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>/* w ww.  j  a v  a  2 s .  co m*/
 *    <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);
    }
}

From source file:org.ow2.bonita.facade.rest.apachehttpclient.ApacheHttpClientUtil.java

public static HttpResponse executeHttpConnection(String uri, byte[] content, String optionsHeader,
        String username, String password)
        throws URISyntaxException, IOException, IOException, ClassNotFoundException {
    String serverAddress = HttpRESTUtil.getRESTServerAddress();
    HttpPost post = new HttpPost(serverAddress + uri);

    ByteArrayEntity entity = new ByteArrayEntity(content);
    entity.setContentType("application/octet-stream");
    post.setHeader("options", optionsHeader);
    post.setEntity(entity);/*from  ww w. ja va 2  s. c  om*/

    HttpClient client = ApacheHttpClientUtil.getHttpClient(serverAddress, username, password);
    HttpResponse httpresponse = client.execute(post);
    return httpresponse;
}

From source file:org.fcrepo.mint.HttpPidMinterTest.java

@Test
public void testMintPidNullHttpMethod() throws Exception {
    final HttpPidMinter testMinter = new HttpPidMinter("http://localhost/minter", null, "", "", ".*/", "");

    final HttpClient mockClient = mock(HttpClient.class);
    final HttpResponse mockResponse = mock(HttpResponse.class);
    final ByteArrayEntity entity = new ByteArrayEntity("/foo/bar/baz".getBytes());
    testMinter.client = mockClient;/*from   ww w .  j a va2 s .c  o m*/

    when(mockClient.execute(isA(HttpUriRequest.class))).thenReturn(mockResponse);
    when(mockResponse.getEntity()).thenReturn(entity);

    final String pid = testMinter.get();
    verify(mockClient).execute(isA(HttpUriRequest.class));
    assertEquals(pid, "baz");
}

From source file:org.fcrepo.kernel.impl.identifiers.HttpPidMinterTest.java

@Test
public void testMintPidXPath() throws Exception {
    final HttpPidMinter testMinter = new HttpPidMinter("http://localhost/minter", "POST", "", "", "",
            "/test/id");

    final HttpClient mockClient = mock(HttpClient.class);
    final HttpResponse mockResponse = mock(HttpResponse.class);
    final ByteArrayEntity entity = new ByteArrayEntity("<test><id>baz</id></test>".getBytes());
    testMinter.client = mockClient;/*from w ww  .ja  va  2  s . c om*/

    when(mockClient.execute(isA(HttpUriRequest.class))).thenReturn(mockResponse);
    when(mockResponse.getEntity()).thenReturn(entity);

    final String pid = testMinter.mintPid();
    verify(mockClient).execute(isA(HttpUriRequest.class));
    assertEquals(pid, "baz");
}

From source file:net.gcolin.httpquery.HttpHandlerImpl.java

@Override
public Request put(String uri, byte[] data) {
    HttpPut put = new HttpPut(uri);
    put.setEntity(new ByteArrayEntity(data));
    return new RequestImpl(put);
}

From source file:org.talend.dataprep.api.service.command.preparation.PreparationUpdate.java

private HttpRequestBase onExecute(String id, Preparation preparation) {
    try {//ww w . ja v  a 2s .c  o m
        final byte[] preparationJSONValue = objectMapper.writeValueAsBytes(preparation);
        final HttpPut preparationCreation = new HttpPut(preparationServiceUrl + "/preparations/" + id);
        preparationCreation.setHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE);
        preparationCreation.setEntity(new ByteArrayEntity(preparationJSONValue));
        return preparationCreation;
    } catch (JsonProcessingException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}

From source file:com.photon.phresco.Screens.HttpRequest.java

/**
 * Send the JSON data to specified URL and get the httpResponse back
 *
 * @param sURL//from   w  ww  .  j a  v a2s  .  c om
 * @param jObject
 * @return InputStream
 * @throws IOException
 */
public static InputStream post(String sURL, JSONObject jObject) throws IOException {
    HttpResponse httpResponse = null;
    InputStream is = null;

    HttpPost httpPostRequest = new HttpPost(sURL);
    HttpEntity entity;

    httpPostRequest.setHeader("Accept", "application/json");
    httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json");
    httpPostRequest.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF-8")));
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = TIME_OUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = TIME_OUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpResponse = httpClient.execute(httpPostRequest);

    if (httpResponse != null) {
        entity = httpResponse.getEntity();
        is = entity.getContent();
    }
    return is;
}

From source file:com.devandroid.tkuautowifi.WifiClient.java

public static void login(final Context context, String username, String password,
        final LoginCallback callback) {
    final String url = "http://163.13.8.254/cgi-bin/ace_web_auth.cgi";

    String payload = String.format("username=%s&userpwd=%s", username, password);
    payload += "&login=%E7%99%BB%E5%85%A5";

    ByteArrayEntity entity = null;//from  w ww  .j a va  2 s.  co m
    try {
        entity = new ByteArrayEntity(payload.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    mClient.post(context, url, entity, "application/x-www-form-urlencoded", new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);

            if (statusCode == 200) {
                // if login success, the response contents should
                // contain these words.
                if (content.contains("login_online_detail.php")) {
                    if (callback != null) {
                        callback.onSuccess();
                    }
                } else {
                    if (callback != null) {
                        callback.onFailure(context.getString(R.string.login_error));
                    }
                }
            } else {
                if (callback != null) {
                    callback.onFailure(context.getString(R.string.login_timeout));
                }
            }
        }

        @Override
        public void onFailure(Throwable error, String content) {
            super.onFailure(error, content);

            if (callback != null) {
                callback.onFailure(context.getString(R.string.login_timeout));
            }
        }
    });
}