Example usage for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM

List of usage examples for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM

Introduction

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

Prototype

ContentType APPLICATION_OCTET_STREAM

To view the source code for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM.

Click Source Link

Usage

From source file:org.eclipse.californium.proxy.HttpTranslator.java

/**
 * Generates an HTTP entity starting from a CoAP request. If the coap
 * message has no payload, it returns a null http entity. It takes the
 * payload from the CoAP message and encapsulates it in an entity. If the
 * content-type is recognized, and a mapping is present in the properties
 * file, it is translated to the correspondent in HTTP, otherwise it is set
 * to application/octet-stream. If the content-type has a charset, namely it
 * is printable, the payload is encapsulated in a StringEntity, if not it a
 * ByteArrayEntity is used./* w  ww .  j ava2 s .  co m*/
 * 
 * 
 * @param coapMessage
 *            the coap message
 * 
 * 
 * @return null if the request has no payload * @throws TranslationException
 *         the translation exception
 */
public static HttpEntity getHttpEntity(Message coapMessage) throws TranslationException {
    if (coapMessage == null) {
        throw new IllegalArgumentException("coapMessage == null");
    }

    // the result
    HttpEntity httpEntity = null;

    // check if coap request has a payload
    byte[] payload = coapMessage.getPayload();
    if (payload != null && payload.length != 0) {

        ContentType contentType = null;

        // if the content type is not set, translate with octect-stream
        if (!coapMessage.getOptions().hasContentFormat()) {
            contentType = ContentType.APPLICATION_OCTET_STREAM;
        } else {
            int coapContentType = coapMessage.getOptions().getContentFormat();
            // search for the media type inside the property file
            String coapContentTypeString = HTTP_TRANSLATION_PROPERTIES
                    .getProperty(KEY_COAP_MEDIA + coapContentType);

            // if the content-type has not been found in the property file,
            // try to get its string value (expressed in mime type)
            if (coapContentTypeString == null || coapContentTypeString.isEmpty()) {
                coapContentTypeString = MediaTypeRegistry.toString(coapContentType);

                // if the coap content-type is printable, it is needed to
                // set the default charset (i.e., UTF-8)
                if (MediaTypeRegistry.isPrintable(coapContentType)) {
                    coapContentTypeString += "; charset=UTF-8";
                }
            }

            // parse the content type
            try {
                contentType = ContentType.parse(coapContentTypeString);
            } catch (UnsupportedCharsetException e) {
                LOGGER.finer("Cannot convert string to ContentType: " + e.getMessage());
                contentType = ContentType.APPLICATION_OCTET_STREAM;
            }
        }

        // get the charset
        Charset charset = contentType.getCharset();

        // if there is a charset, means that the content is not binary
        if (charset != null) {
            String body = "";
            try {
                body = new String(payload, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            body = body.replace("coap://", "http://" + proxyIP + ":8080/proxy/");
            payload = body.getBytes();
            // according to the class ContentType the default content-type
            // with UTF-8 charset is application/json. If the content-type
            // parsed is different and is not iso encoded, a translation is
            // needed
            Charset isoCharset = ISO_8859_1;
            /*if (!charset.equals(isoCharset) && !contentType.getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) {
               byte[] newPayload = changeCharset(payload, charset, isoCharset);
                    
               // since ISO-8859-1 is a subset of UTF-8, it is needed to
               // check if the mapping could be accomplished, only if the
               // operation is succesful the payload and the charset should
               // be changed
               if (newPayload != null) {
                  payload = newPayload;
                  // if the charset is changed, also the entire
                  // content-type must change
                  contentType = ContentType.create(contentType.getMimeType(), isoCharset);
               }
            }*/

            // create the content
            String payloadString = new String(payload, contentType.getCharset());

            // create the entity
            httpEntity = new StringEntity(payloadString,
                    ContentType.create(contentType.getMimeType(), contentType.getCharset()));
        } else {
            // create the entity
            httpEntity = new ByteArrayEntity(payload);
        }

        // set the content-type
        ((AbstractHttpEntity) httpEntity).setContentType(contentType.getMimeType());
    }

    return httpEntity;
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.v2.AeriServer.java

public ServerResponse upload(ErrorReport report, IProgressMonitor monitor) throws IOException {
    String body = Reports.toJson(report, false);
    StringEntity stringEntity = new StringEntity(body, ContentType.APPLICATION_OCTET_STREAM.withCharset(UTF_8));
    // length of zipped conent is unknown, using the progress of the string-stream instead.
    // download progress percentage will be accurate, download progress size will be too large by the compression factor
    HttpEntity entity = new GzipCompressingEntity(
            Responses.decorateForProgressMonitoring(stringEntity, monitor));

    String submitUrl = configuration.getSubmitUrl();
    URI target = newURI(submitUrl);
    // @formatter:off
    Request request = Request.Post(target).viaProxy(getProxyHost(target).orNull()).body(entity)
            .connectTimeout(configuration.getConnectTimeoutMs()).staleConnectionCheck(true)
            .socketTimeout(configuration.getSocketTimeoutMs());
    // @formatter:on
    String response = proxyAuthentication(executor, target).execute(request).returnContent().asString();
    ServerResponse05 response05 = Json.deserialize(response, ServerResponse05.class);

    // TODO complete dto
    ServerResponse result = new ServerResponse();
    result.setReportTitle(abbreviate(report.getStatus().getMessage(), 80));
    result.setIncidentId(response05.getBugId().orNull());
    result.setIncidentUrl(response05.getBugUrl().orNull());
    result.setResolution(tryParse(response05));
    result.setCommitterMessage(response05.getInformation().orNull());
    return result;
}

From source file:org.flowable.ui.admin.service.engine.AppDeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, "app-repository/deployments"));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, name)
            .build();/*from  w w  w .j  av a  2 s. c o  m*/
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}

From source file:org.flowable.ui.admin.service.engine.CmmnDeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, "cmmn-repository/deployments"));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, name)
            .build();//  w  w  w .j  a v  a2s.c om
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}

From source file:org.flowable.ui.admin.service.engine.DecisionTableDeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, "dmn-repository/deployments"));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, name)
            .build();/* ww w .  j ava2 s .  c o  m*/
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}

From source file:org.flowable.ui.admin.service.engine.DeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {

    String deploymentKey = null;/*  w  w w .  ja va2  s.com*/
    String deploymentName = null;

    byte[] inputStreamByteArray = IOUtils.toByteArray(inputStream);

    // special handling for exported bar files
    if (name != null && (name.endsWith(".zip") || name.endsWith(".bar"))) {
        JsonNode appDefinitionJson = getAppDefinitionJson(new ByteArrayInputStream(inputStreamByteArray));

        if (appDefinitionJson != null) {
            if (appDefinitionJson.has("key") && appDefinitionJson.get("key") != null) {
                deploymentKey = appDefinitionJson.get("key").asText();
            }
            if (appDefinitionJson.has("name") && appDefinitionJson.get("name") != null) {
                deploymentName = appDefinitionJson.get("name").asText();
            }
        }
    }

    URIBuilder uriBuilder = clientUtil.createUriBuilder("repository/deployments");

    if (StringUtils.isNotEmpty(deploymentKey)) {
        uriBuilder.addParameter("deploymentKey", encode(deploymentKey));
    }
    if (StringUtils.isNotEmpty(deploymentName)) {
        uriBuilder.addParameter("deploymentName", encode(deploymentName));
    }

    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, uriBuilder));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, inputStreamByteArray, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}

From source file:org.olat.restapi.RestConnection.java

public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file)
        throws UnsupportedEncodingException {

    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addTextBody("filename", filename)
            .addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, filename).build();
    post.setEntity(entity);/*from ww  w  .ja v a  2 s.co  m*/
}

From source file:ste.web.http.handlers.BugFreeFileHandler.java

@Test
public void default_mime_type_is_octet_binary() throws Exception {
    FileHandler h = new FileHandler("src/test/mime");

    BasicHttpRequest request = HttpUtils.getSimpleGet("/test.bin");
    BasicHttpResponse response = HttpUtils.getBasicResponse();

    h.handle(request, response, new HttpSessionContext());

    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue())
            .isEqualTo(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
}

From source file:ste.web.http.handlers.FileHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    checkHttpMethod(request);//from   www .ja  va  2  s  .  c o  m

    String target = request.getRequestLine().getUri();

    for (String exclude : excludePatterns) {
        if (target.matches(exclude)) {
            notFound(target, response);

            return;
        }
    }
    if (StringUtils.isNotBlank(webContext) && target.startsWith(webContext)) {
        target = target.substring(webContext.length());
    }

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
    }

    URI uri = null;
    try {
        uri = new URI(target);
    } catch (URISyntaxException x) {
        throw new HttpException("malformed URL '" + target + "'");
    }
    final File file = new File(this.docRoot, uri.getPath());
    if (!file.exists()) {
        notFound(target, response);
    } else if (!file.canRead() || file.isDirectory()) {
        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        StringEntity entity = new StringEntity("<html><body><h1>Access denied</h1></body></html>",
                ContentType.TEXT_HTML);
        response.setEntity(entity);
    } else {
        response.setStatusCode(HttpStatus.SC_OK);

        String mimeType = MimeUtils.getInstance().getMimeType(file);
        ContentType type = MimeUtils.MIME_UNKNOWN.equals(mimeType) ? ContentType.APPLICATION_OCTET_STREAM
                : ContentType.create(mimeType);
        FileEntity body = new FileEntity(file, type);
        response.setEntity(body);
    }
}

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

public static String doPost(String requestUrl, Map<String, String> paramsMap, Map<String, InputStream> files)
        throws Exception {

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(500)
            .setSocketTimeout(20000).setConnectTimeout(20000).build();

    // ?//  w  ww .  j  a va 2 s .  com
    MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName(charset));

    if (paramsMap != null) {
        Set<Entry<String, String>> paramsSet = paramsMap.entrySet();
        for (Entry<String, String> entry : paramsSet) {
            mbuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", charset));
        }
    }

    if (files != null) {
        Set<Entry<String, InputStream>> filesSet = files.entrySet();
        for (Entry<String, InputStream> entry : filesSet) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            InputStream is = entry.getValue();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.close();
            is.close();
            mbuilder.addBinaryBody("attachment", os.toByteArray(), ContentType.APPLICATION_OCTET_STREAM,
                    entry.getKey());
        }
    }

    HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setConfig(requestConfig);

    HttpEntity httpEntity = mbuilder.build();

    httpPost.setEntity(httpEntity);

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };

    return httpClient.execute(httpPost, responseHandler);
}