Example usage for org.apache.http.protocol HTTP CONTENT_TYPE

List of usage examples for org.apache.http.protocol HTTP CONTENT_TYPE

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP CONTENT_TYPE.

Prototype

String CONTENT_TYPE

To view the source code for org.apache.http.protocol HTTP CONTENT_TYPE.

Click Source Link

Usage

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceJsonTable.java

/**
 * Updates an element from a Mobile Service Table
 * // w  w w.  j a v a  2 s  .  com
 * @param element
 *            The JsonObject to update
 * @param parameters
 *            A list of user-defined parameters and values to include in the request URI query string
 * @param callback
 *            Callback to invoke when the operation is completed
 */
public void update(final JsonObject element, List<Pair<String, String>> parameters,
        final TableJsonOperationCallback callback) {
    Object id = null;
    String version = null;
    String content = null;

    try {
        id = validateId(element);
    } catch (Exception e) {
        if (callback != null) {
            callback.onCompleted(null, e, null);
        }

        return;
    }

    if (!isNumericType(id)) {
        version = getVersionSystemProperty(element);
        content = removeSystemProperties(element).toString();
    } else {
        content = element.toString();
    }

    ServiceFilterRequest patch;

    Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
    uriBuilder.path(TABLES_URL);
    uriBuilder.appendPath(mTableName);
    uriBuilder.appendPath(id.toString());

    parameters = addSystemProperties(mSystemProperties, parameters);

    if (parameters != null && parameters.size() > 0) {
        for (Pair<String, String> parameter : parameters) {
            uriBuilder.appendQueryParameter(parameter.first, parameter.second);
        }
    }

    patch = new ServiceFilterRequestImpl(new HttpPatch(uriBuilder.build().toString()),
            mClient.getAndroidHttpClientFactory());
    patch.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE);

    if (version != null) {
        patch.addHeader("If-Match", getEtagFromValue(version));
    }

    try {
        patch.setContent(content);
    } catch (Exception e) {
        if (callback != null) {
            callback.onCompleted(null, e, null);
        }

        return;
    }

    executeTableOperation(patch, new TableJsonOperationCallback() {

        @Override
        public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) {
            if (callback != null) {
                if (exception == null && jsonEntity != null) {
                    JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, jsonEntity);

                    updateVersionFromETag(response, patchedJson);

                    callback.onCompleted(patchedJson, exception, response);
                } else if (exception != null && response != null && response.getStatus() != null
                        && response.getStatus().getStatusCode() == 412) {
                    String content = response.getContent();

                    JsonObject serverEntity = null;

                    if (content != null) {
                        serverEntity = new JsonParser().parse(content).getAsJsonObject();
                    }

                    callback.onCompleted(jsonEntity,
                            new MobileServicePreconditionFailedExceptionBase(exception, serverEntity),
                            response);
                } else {
                    callback.onCompleted(jsonEntity, exception, response);
                }
            }
        }
    });
}

From source file:org.apache.synapse.transport.nhttp.ClientWorker.java

/**
 * Process the received response through Axis2
 *//*from  w  ww .  ja v a2  s .  c om*/
public void run() {

    CustomLogSetter.getInstance().clearThreadLocalContent();
    setServerContextAttribute(NhttpConstants.CLIENT_WORKER_START_TIME, System.currentTimeMillis(), outMsgCtx);

    // to support Sandesha.. if there isn't a response message context, we cannot read any
    // response and populate it with the soap envelope
    if (responseMsgCtx == null) {
        return;
    }

    try {
        if (in != null) {
            Header cType = response.getFirstHeader(HTTP.CONTENT_TYPE);
            String contentType;
            if (cType != null) {
                // This is the most common case - Most of the time servers send the Content-Type
                contentType = cType.getValue();
            } else {
                // Server hasn't sent the header - Try to infer the content type
                contentType = inferContentType();
            }

            String charSetEnc = BuilderUtil.getCharSetEncoding(contentType);
            if (charSetEnc == null) {
                charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
            }

            responseMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);

            // workaround for Axis2 TransportUtils.createSOAPMessage() issue, where a response
            // of content type "text/xml" is thought to be REST if !MC.isServerSide(). This
            // question is still under debate and due to the timelines, I am commiting this
            // workaround as Axis2 1.2 is about to be released and Synapse 1.0
            responseMsgCtx.setServerSide(false);
            SOAPEnvelope envelope;
            try {
                envelope = TransportUtils.createSOAPMessage(responseMsgCtx,
                        HTTPTransportUtils.handleGZip(responseMsgCtx, in), contentType);

            } catch (OMException e) {
                // handle non SOAP and POX/REST payloads (probably text/html)
                String errorMessage = "Unexpected response received. HTTP response code : "
                        + this.response.getStatusLine().getStatusCode() + " HTTP status : "
                        + this.response.getStatusLine().getReasonPhrase() + " exception : " + e.getMessage();

                log.warn(errorMessage);
                if (log.isDebugEnabled()) {
                    log.debug(errorMessage, e);
                    log.debug("Creating the SOAPFault to be injected...");
                }
                SOAPFactory factory = new SOAP11Factory();
                envelope = factory.getDefaultFaultEnvelope();
                SOAPFaultDetail detail = factory.createSOAPFaultDetail();
                detail.setText(errorMessage);
                envelope.getBody().getFault().setDetail(detail);
                SOAPFaultReason reason = factory.createSOAPFaultReason();
                reason.setText(errorMessage);
                envelope.getBody().getFault().setReason(reason);
                SOAPFaultCode code = factory.createSOAPFaultCode();
                code.setText(Integer.toString(this.response.getStatusLine().getStatusCode()));
                envelope.getBody().getFault().setCode(code);
            }
            responseMsgCtx.setServerSide(true);
            responseMsgCtx.setEnvelope(envelope);

        } else {
            // there is no response entity-body
            responseMsgCtx.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
            responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
        }

        // copy the HTTP status code as a message context property with the key HTTP_SC to be
        // used at the sender to set the propper status code when passing the message
        int statusCode = this.response.getStatusLine().getStatusCode();
        responseMsgCtx.setProperty(NhttpConstants.HTTP_SC, statusCode);
        if (statusCode >= 400) {
            responseMsgCtx.setProperty(NhttpConstants.FAULT_MESSAGE, NhttpConstants.TRUE);
        }
        responseMsgCtx.setProperty(NhttpConstants.NON_BLOCKING_TRANSPORT, true);
        if (endpointURLPrefix != null) {
            responseMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, endpointURLPrefix);
        }

        // process response received
        try {
            AxisEngine.receive(responseMsgCtx);
        } catch (AxisFault af) {
            // This will be reached if an exception is thrown within an Axis2 handler
            String errorMessage = "Fault processing response message through Axis2: " + af.getMessage();

            log.warn(errorMessage);
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, af);
                log.debug("Directly invoking SynapseCallbackReceiver after setting " + "error properties");
            }

            responseMsgCtx.setProperty(NhttpConstants.SENDING_FAULT, Boolean.TRUE);
            responseMsgCtx.setProperty(NhttpConstants.ERROR_CODE, NhttpConstants.RESPONSE_PROCESSING_FAILURE);
            responseMsgCtx.setProperty(NhttpConstants.ERROR_MESSAGE, errorMessage.split("\n")[0]);
            responseMsgCtx.setProperty(NhttpConstants.ERROR_DETAIL, JavaUtils.stackToString(af));
            responseMsgCtx.setProperty(NhttpConstants.ERROR_EXCEPTION, af);
            responseMsgCtx.getAxisOperation().getMessageReceiver().receive(responseMsgCtx);
        }

    } catch (AxisFault af) {
        log.error("Fault creating response SOAP envelope", af);
        return;
    } catch (XMLStreamException e) {
        log.error("Error creating response SOAP envelope", e);
    } catch (IOException e) {
        log.error("Error closing input stream from which message was read", e);

    } finally {
        // this is the guaranteed location to close the RESPONSE_SOURCE_CHANNEL that was used
        // to read the response back from the server.
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ignore) {
        }
    }
}

From source file:com.getblimp.api.client.Blimp.java

private StringEntity createStringEntity(BlimpObject data) throws UnsupportedEncodingException {
    StringEntity entity = new StringEntity(data.toJson());
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    return entity;
}

From source file:com.azure.webapi.LoginManager.java

/**
 * Invokes Windows Azure Mobile Services authentication using the specified
 * token//from   w  ww  .j  av  a 2  s.c  o m
 * 
 * @param token
 *            The token used for authentication
 * @param url
 *            The URL used for the authentication process
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
private void authenticateWithToken(String token, String url, final UserAuthenticationCallback callback) {
    if (token == null) {
        throw new IllegalArgumentException("token can not be null");
    }

    if (url == null) {
        throw new IllegalArgumentException("url can not be null");
    }

    // Create a request
    final ServiceFilterRequest request = new ServiceFilterRequestImpl(new HttpPost(url));
    request.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE);

    try {
        // Set request's content with the token
        request.setContent(token);
    } catch (Exception e) {
        // this should never happen
    }
    final MobileServiceConnection connection = mClient.createConnection();

    // Create the AsyncTask that will execute the request
    new RequestAsyncTask(request, connection) {
        @Override
        protected void onPostExecute(ServiceFilterResponse response) {
            if (callback != null) {

                if (mTaskException == null && response != null) {
                    MobileServiceUser user = null;
                    try {
                        // Get the user from the response and create a
                        // MobileServiceUser object from the JSON
                        String content = response.getContent();
                        user = createUserFromJSON((JsonObject) new JsonParser().parse((content.trim())));

                    } catch (Exception e) {
                        // Something went wrong, call onCompleted method
                        // with exception
                        callback.onCompleted(null,
                                new MobileServiceException("Error while authenticating user.", e), response);
                        return;
                    }

                    // Call onCompleted method
                    callback.onCompleted(user, null, response);
                } else {
                    // Something went wrong, call onCompleted method with
                    // exception
                    callback.onCompleted(null,
                            new MobileServiceException("Error while authenticating user.", mTaskException),
                            response);
                }
            }
        }
    }.execute();
}

From source file:com.azure.webapi.MobileServiceJsonTable.java

/**
 * Updates an element from a Mobile Service Table
 * /*from   ww w.jav a2  s. co m*/
 * @param element
 *            The JsonObject to update
 * @param parameters
 *            A list of user-defined parameters and values to include in the request URI query string
 * @param callback
 *            Callback to invoke when the operation is completed
 */
public void update(final JsonObject element, final List<Pair<String, String>> parameters,
        final TableJsonOperationCallback callback) {

    try {
        updateIdProperty(element);

        if (!element.has("id") || element.get("id").getAsInt() == 0) {
            throw new IllegalArgumentException(
                    "You must specify an id property with a valid value for updating an object.");
        }
    } catch (Exception e) {
        if (callback != null) {
            callback.onCompleted(null, e, null);
        }
        return;
    }

    String content = element.toString();

    ServiceFilterRequest putRequest;
    try {
        Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
        uriBuilder.path(TABLES_URL); //This needs to reference to "api/"
        uriBuilder.appendPath(URLEncoder.encode(mTableName, MobileServiceClient.UTF8_ENCODING));
        uriBuilder.appendPath(Integer.valueOf(getObjectId(element)).toString());

        if (parameters != null && parameters.size() > 0) {
            for (Pair<String, String> parameter : parameters) {
                uriBuilder.appendQueryParameter(parameter.first, parameter.second);
            }
        }
        putRequest = new ServiceFilterRequestImpl(new HttpPut(uriBuilder.build().toString()));
        putRequest.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE);

    } catch (UnsupportedEncodingException e) {
        if (callback != null) {
            callback.onCompleted(null, e, null);
        }
        return;
    }

    try {
        putRequest.setContent(content);
    } catch (Exception e) {
        if (callback != null) {
            callback.onCompleted(null, e, null);
        }
        return;
    }

    executeTableOperation(putRequest, new TableJsonOperationCallback() {

        // TODO webapi is different in response. It return status code only
        @Override
        public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) {
            if (callback != null) {
                if (exception == null && jsonEntity != null) {
                    JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, jsonEntity);
                    callback.onCompleted(patchedJson, exception, response);
                } else {
                    callback.onCompleted(jsonEntity, exception, response);
                }
            }
        }
    });
}

From source file:eu.vital.TrustManager.connectors.ppi.PPIManager.java

private JSONArray getPPIObservations(String ppi_url, String body) throws ParseException {
    JSONArray data = new JSONArray();
    HttpClientBuilder builder = HttpClientBuilder.create();
    try {//from www .j  av a 2 s.  c o  m

        final CloseableHttpClient client = builder.build();

        HttpPost post = new HttpPost(ppi_url);
        post.setHeader(HTTP.CONTENT_TYPE, "application/json");

        HttpEntity entity = new StringEntity(body);
        post.setEntity(entity);

        HttpResponse clientresponse = client.execute(post);
        if (clientresponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            return null;
        final String sdata = EntityUtils.toString(clientresponse.getEntity(), StandardCharsets.UTF_8);
        data = new JSONArray(sdata);
    } catch (IOException ioe) {
        //logger.error(ioe);
    }

    return data;
}

From source file:ddf.catalog.test.TestFederation.java

private String ingest(String data, String mimeType)
        throws UnsupportedEncodingException, IOException, ClientProtocolException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost postCall = new HttpPost(REST_PATH);
    postCall.setEntity(new StringEntity(data));
    postCall.setHeader(HTTP.CONTENT_TYPE, mimeType);
    HttpResponse postResponse = httpclient.execute(postCall);
    EntityUtils.consume(postResponse.getEntity());
    String id = postResponse.getFirstHeader("id").getValue();
    assertTrue("Ingest failed, Header not returned.", id != null);
    return id;/*www .j  a va  2  s .c  o  m*/

}

From source file:com.facebook.stetho.inspector.network.NetworkEventReporterImpl.java

@Nullable
private String getContentType(InspectorHeaders headers) {
    // This may need to change in the future depending on how cumbersome header simulation
    // is for the various hooks we expose.
    return headers.firstHeaderValue(HTTP.CONTENT_TYPE);
}

From source file:org.opendatakit.http.conn.GaeManagedClientConnection.java

@Override
public void receiveResponseEntity(HttpResponse resp) throws HttpException, IOException {
    if (resp == null) {
        throw new IllegalArgumentException("HttpResponse cannot be null");
    }/*from w w w. jav a  2 s .c o m*/
    if (response == null) {
        throw new IllegalStateException("no response avaliable");
    }

    byte[] byteArray = response.getContent();
    if (byteArray != null) {
        ByteArrayEntity entity = new ByteArrayEntity(response.getContent());
        entity.setContentType(resp.getFirstHeader(HTTP.CONTENT_TYPE));
        resp.setEntity(entity);
    }
}

From source file:ai.eve.volley.Request.java

/**
 * Returns the raw POST or PUT body to be sent.
 * /*  w w w.  j a  va2 s. co  m*/
 * @throws AuthFailureError
 *             in the event of auth failure
 */
public void getBody(HttpURLConnection connection) throws AuthFailureError {
    Map<String, String> params = getParams();
    if (params != null && params.size() > 0) {
        byte[] bs = encodeParameters(params, getParamsEncoding());
        try {
            if (bs != null) {
                connection.setDoOutput(true);
                connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(bs);
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}