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:org.deviceconnect.message.http.impl.factory.AbstractHttpMessageFactory.java

/**
 * dConnect?HTTP??./*from   w w  w.  j av  a  2  s.  c o m*/
 * @param dmessage dConnect
 * @return HTTP
 */
protected HttpEntity createHttpEntity(final DConnectMessage dmessage) {
    mLogger.entering(getClass().getName(), "createHttpEntity", dmessage);

    HttpEntity entity = null;
    try {
        DConnectMessage message = new BasicDConnectMessage(dmessage);
        message.remove(DConnectMessage.EXTRA_PROFILE);
        message.remove(DConnectMessage.EXTRA_INTERFACE);
        message.remove(DConnectMessage.EXTRA_ATTRIBUTE);
        message.remove(DConnectMessage.EXTRA_METHOD);

        entity = new ByteArrayEntity(message.toString(2).getBytes(HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        mLogger.log(Level.FINE, e.toString(), e);
        mLogger.warning(e.toString());
    }

    mLogger.exiting(getClass().getName(), "createHttpEntity", entity);
    return entity;
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

private static HTTPRequestResponse doPOST(ClientConnectionManager connectionManager, String requestURL,
        RESTActivityConfigurationBean configBean, Object inputMessageBody, Map<String, String> urlParameters,
        CredentialsProvider credentialsProvider) {
    HttpPost httpPost = new HttpPost(requestURL);

    // TODO - decide whether this is needed for PUT requests, too (or just
    // here, for POST)
    // check whether to send the HTTP Expect header or not
    if (!configBean.getSendHTTPExpectRequestHeader())
        httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    // If the user wants to set MIME type for the 'Content-Type' header
    if (!configBean.getContentTypeForUpdates().isEmpty())
        httpPost.setHeader(CONTENT_TYPE_HEADER_NAME, configBean.getContentTypeForUpdates());
    try {/*from w  w w  . j ava  2  s.  c om*/
        HttpEntity entity = null;
        if (inputMessageBody == null) {
            entity = new StringEntity("");
        } else if (configBean.getOutgoingDataFormat() == DATA_FORMAT.String) {
            entity = new StringEntity((String) inputMessageBody);
        } else {
            entity = new ByteArrayEntity((byte[]) inputMessageBody);
        }
        httpPost.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        return (new HTTPRequestResponse(new Exception("Error occurred while trying to "
                + "attach a message body to the POST request. See attached cause of this "
                + "exception for details.")));
    }
    return performHTTPRequest(connectionManager, httpPost, configBean, urlParameters, credentialsProvider);
}

From source file:org.gbif.registry.metasync.protocols.biocase.BiocaseMetadataSynchroniserTest.java

/**
 * Prepares a {@link HttpResponse} with the given response status and the content of the file.
 *//*from  ww w.  j  a va  2s. c  o  m*/
private HttpResponse prepareResponse(int responseStatus, String fileName) throws IOException {
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseStatus, ""));
    response.setStatusCode(responseStatus);
    byte[] bytes = Resources.toByteArray(Resources.getResource(fileName));
    response.setEntity(new ByteArrayEntity(bytes));
    return response;
}

From source file:com.zzl.zl_app.connection.Utility.java

/**
 * Implement a weibo http request and return results .
 * /*from w  ww  .j a v  a 2 s  .c o m*/
 * @param context
 *            context of activity
 * @param url
 * @param method
 *            (GET|POST)
 * @param bm
 * @return
 * @throws Exception
 */
public static String openUrl(Context context, String url, String method, Bitmap bm) throws Exception {
    String result = "";
    try {
        HttpClient client = getNewHttpClient(context);
        HttpUriRequest request = null;
        ByteArrayOutputStream bos = null;
        if (method.equals("GET")) {

        } else if (method.equals("POST")) {
            Log.i("IO", url);
            HttpPost post = new HttpPost(url);
            byte[] data = null;
            bos = new ByteArrayOutputStream(1024 * 50);
            post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
            Utility.imageContentToUpload(bos, bm);
            data = bos.toByteArray();
            bos.close();
            // UrlEncodedFormEntity entity = getPostParamters(params);
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
            request = post;
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(url);
        }
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if (statusCode != 200) {
            result = read(response);
            throw new Exception();
        }
        // parse content stream from response
        result = read(response);
        return result;
    } catch (IOException e) {

    }
    return "";
}

From source file:org.n52.sos.service.it.SosV1IT.java

/**
 * Send a test V1 GetObservation request with a resultTemplate responseMode.
 * Includes a TM_During temporal filter. V1 GetResult is tested using the
 * returned observation template id.// w w  w  .jav  a  2  s . c  om
 * 
 * @throws IOException
 * @throws URISyntaxException
 * @throws IllegalStateException
 * @throws XmlException
 * @throws SAXException
 * @throws OwsExceptionReport
 */
@Ignore
@Test
public void getObservationResultTemplateV1() throws IOException, URISyntaxException, IllegalStateException,
        XmlException, SAXException, OwsExceptionReport {
    // create request document
    GetObservationDocument xb_getObsDoc = GetObservationDocument.Factory.newInstance();
    GetObservation xb_getObs = xb_getObsDoc.addNewGetObservation();
    xb_getObs.setService(SosConstants.SOS);
    xb_getObs.setVersion(Sos1Constants.SERVICEVERSION);
    xb_getObs.setSrsName("urn:ogc:def:crs:EPSG::4326");
    xb_getObs.setOffering("GAUGE_HEIGHT");
    xb_getObs.setObservedPropertyArray(new String[] { "urn:ogc:def:phenomenon:OGC:1.0.30:waterlevel" });
    xb_getObs.setResponseFormat(OMConstants.CONTENT_TYPE_OM);
    xb_getObs.setResponseMode(ResponseModeType.RESULT_TEMPLATE);
    TimePeriod tp = new TimePeriod();
    tp.setStart(new DateTime(2008, 3, 27, 0, 0, 0, 0));
    tp.setEnd(new DateTime(2008, 4, 3, 0, 0, 0, 0));
    TemporalFilter tf = new TemporalFilter(FilterConstants.TimeOperator.TM_During, tp, null);
    ITRequestEncoder.encodeTemporalFilter(tf, xb_getObs.addNewEventTime());

    // get response
    HttpPost httppost = new HttpPost(getSOSURI());
    byte[] xmlBytes = IOUtils.toByteArray(xb_getObsDoc.newInputStream());
    httppost.setEntity(new ByteArrayEntity(xmlBytes));
    HttpResponse response = client.execute(httppost);
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    assertNotNull(response.getEntity());
    ObservationCollectionDocument xb_obsColDoc = ObservationCollectionDocument.Factory
            .parse(response.getEntity().getContent());
    assertNotNull(xb_obsColDoc);

    // validate response using javax.xml.validation schema validation
    getXmlValidator().validate(new StreamSource(xb_obsColDoc.newInputStream()));

    ObservationCollectionType xb_obsCol = xb_obsColDoc.getObservationCollection();
    assertNotNull(xb_obsCol);

    // run GetResult tests for latest observations
    ObservationPropertyType[] xb_observations = xb_obsCol.getMemberArray();
    for (int i = 0; i < xb_observations.length; i++) {
        ObservationType xb_obs = xb_observations[i].getObservation();
        CodeType[] xb_names = xb_obs.getNameArray();
        for (int j = 0; j < xb_names.length; j++) {
            String name = xb_names[j].getStringValue();
            if (name.startsWith(SosConstants.OBS_TEMP_ID_PREFIX)) {
                getLatestResultV1(name);
            }
        }
    }
}

From source file:org.vuphone.wwatch.asterisk.AsteriskConnector.java

/**
 * This is a helper method for playRecordingToPSTNNumber that will
 * create a new SIP extension to dial the telephone number provided.
 * //from ww  w. j  a  va2 s . co  m
 * @param number - a String representation of a 10 digit telephone
 * number that will be dialed from the newly created extension.
 * 
 * @return - a String representation of the extension number that
 * will dial the provided telephone number, or an empty String ""
 * if there is an error creating the extension.
 */
private static String createSipExtension(String number) {

    String extension = "";

    // The first post will open the screen to create a new generic
    // SIP extension
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://" + SERVER + "/admin/config.php?type=setup&display=extensions");
    String authorization = Base64.base64Encode(MAINT_USERNAME + ":" + MAINT_PASSWORD);
    post.addHeader("Authorization", "Basic " + authorization);
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String info = "display=extensions&type=setup&tech_hardware=sip_generic&Submit=Submit";
    ByteArrayEntity str = new ByteArrayEntity(info.getBytes());
    post.setEntity(str);

    try {
        c.execute(post);

    } catch (ClientProtocolException e) {

        e.printStackTrace();
        return extension;
    } catch (IOException e) {

        e.printStackTrace();
        return extension;
    }

    // The second post will create the new extension and set it to dial
    // the provided number.  It will be named Extension<number>, with
    // password <number>-password.
    HttpClient c1 = new DefaultHttpClient();
    post = new HttpPost("http://" + SERVER + "/admin/config.php");
    post.addHeader("Authorization", "Basic " + authorization);
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String extenNum = number;
    String extenName = "Extension" + extenNum;
    String extenSecret = extenNum + "-password";
    info = "display=extensions&type=setup&action=add&extdisplay=&action=add&extdisplay=&extension=" + extenNum
            + "&name=" + extenName
            + "&cid_masquerade=&sipname=&directdid=&didalert=&mohclass=default&outboundcid=&ringtimer=0&callwaiting=enabled&emergency_cid=&tech=sip&hardware=generic&devinfo_secret="
            + extenSecret
            + "&devinfo_dtmfmode=rfc2833&devinfo_canreinvite=no&devinfo_context=from-internal&devinfo_host=dynamic&devinfo_type=friend&devinfo_nat=yes&devinfo_port=5060&devinfo_qualify=yes&devinfo_callgroup=&devinfo_pickupgroup=&devinfo_disallow=&devinfo_allow=&devinfo_dial="
            + number
            + "&devinfo_accountcode=&devinfo_mailbox=&faxexten=default&faxemail=&answer=0&wait=0&privacyman=0&in_default_page_grp=0&langcode=&record_in=Adhoc&record_out=Adhoc&vm=disabled&vmpwd=&email=&pager=&attach=attach%3Dno&saycid=saycid%3Dno&envelope=envelope%3Dno&delete=delete%3Dno&options=&vmcontext=default&vmx_state=&Submit=Submit";
    str = new ByteArrayEntity(info.getBytes());
    post.setEntity(str);

    try {
        c1.execute(post);

    } catch (ClientProtocolException e) {

        e.printStackTrace();
        return extension;
    } catch (IOException e) {

        e.printStackTrace();
        return extension;
    }

    // The third post will submit the changes.
    HttpClient c2 = new DefaultHttpClient();
    post = new HttpPost("http://" + SERVER + "/admin/config.php");
    post.addHeader("Authorization", "Basic " + authorization);
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    info = "handler=reload";
    str = new ByteArrayEntity(info.getBytes());
    post.setEntity(str);

    try {
        c2.execute(post);

    } catch (ClientProtocolException e) {

        e.printStackTrace();
        return extension;
    } catch (IOException e) {

        e.printStackTrace();
        return extension;
    }

    extension = "SIP/" + extenNum;
    System.out.println("I'm going to return: " + extension);
    return extension;
}

From source file:org.darwinathome.client.HttpHub.java

public void setGenome(final Genome genome, final Exchange exchange) {
    submit(new ExchangeRunner(Hub.SET_GENOME_SERVICE, exchange) {
        @Override//  w  w  w . j  a  v a  2  s  . c  o  m
        HttpRequestBase getRequest(String serviceUrl) {
            HttpPost post = new HttpPost(serviceUrl);
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
                genome.write(dos);
                dos.close();
                ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
                entity.setContentType("application/octet-stream");
                post.setEntity(entity);
            } catch (IOException e) {
                log.warn("Problem marshalling", e);
                exchange.fail(Failure.MARSHALLING);
            }
            return post;
        }
    });
}

From source file:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java

protected HttpEntity createHttpRequestEntity(UpnpMessage<?> upnpMessage) {
    if (upnpMessage.getBodyType().equals(UpnpMessage.BodyType.BYTES)) {
        if (log.isLoggable(Level.FINE))
            log.fine("Preparing HTTP request entity as byte[]");
        return new ByteArrayEntity(upnpMessage.getBodyBytes());
    } else {/*from w  w  w  .  j a  v a  2s  .  c om*/
        if (log.isLoggable(Level.FINE))
            log.fine("Preparing HTTP request entity as string");
        try {
            String charset = upnpMessage.getContentTypeCharset();
            return new StringEntity(upnpMessage.getBodyString(), charset != null ? charset : "UTF-8");
        } catch (Exception ex) {
            // WTF else am I supposed to do with this exception?
            throw new RuntimeException(ex);
        }
    }
}