List of usage examples for org.apache.http.protocol HTTP CONTENT_TYPE
String CONTENT_TYPE
To view the source code for org.apache.http.protocol HTTP CONTENT_TYPE.
Click Source Link
From source file:org.apache.synapse.transport.passthru.ServerWorker.java
public void run() { CustomLogSetter.getInstance().clearThreadLocalContent(); request.getConnection().getContext().setAttribute(NhttpConstants.SERVER_WORKER_START_TIME, System.currentTimeMillis()); if (log.isDebugEnabled()) { log.debug("Starting a new Server Worker instance"); }//from w w w.jav a2 s . c o m String method = request.getRequest() != null ? request.getRequest().getRequestLine().getMethod().toUpperCase() : ""; processHttpRequestUri(msgContext, method); //For requests to fetch wsdl, return the message flow without going through the normal flow if (isRequestToFetchWSDL()) { return; } //need special case to handle REST boolean isRest = isRESTRequest(msgContext, method); //should be process normally if (!isRest) { if (request.isEntityEnclosing()) { processEntityEnclosingRequest(msgContext, true); } else { processNonEntityEnclosingRESTHandler(null, msgContext, true); } } else { String contentTypeHeader = request.getHeaders().get(HTTP.CONTENT_TYPE); SOAPEnvelope soapEnvelope = this.handleRESTUrlPost(contentTypeHeader); processNonEntityEnclosingRESTHandler(soapEnvelope, msgContext, true); } sendAck(msgContext); }
From source file:org.apache.synapse.transport.passthru.ServerWorker.java
public void processEntityEnclosingRequest(MessageContext msgContext, boolean injectToAxis2Engine) { try {/*from w ww .j a v a2 s. com*/ String contentTypeHeader = request.getHeaders().get(HTTP.CONTENT_TYPE); contentTypeHeader = contentTypeHeader != null ? contentTypeHeader : inferContentType(); String charSetEncoding = null; String contentType = null; if (contentTypeHeader != null) { charSetEncoding = BuilderUtil.getCharSetEncoding(contentTypeHeader); contentType = TransportUtils.getContentType(contentTypeHeader, msgContext); } // get the contentType of char encoding if (charSetEncoding == null) { charSetEncoding = MessageContext.DEFAULT_CHAR_SET_ENCODING; } String method = request.getRequest() != null ? request.getRequest().getRequestLine().getMethod().toUpperCase() : ""; msgContext.setTo(new EndpointReference(request.getUri())); msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEncoding); msgContext.setServerSide(true); msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentTypeHeader); msgContext.setProperty(Constants.Configuration.MESSAGE_TYPE, contentType); if (contentTypeHeader == null || HTTPTransportUtils.isRESTRequest(contentTypeHeader) || isRest(contentTypeHeader)) { msgContext.setProperty(PassThroughConstants.REST_REQUEST_CONTENT_TYPE, contentType); msgContext.setDoingREST(true); SOAPEnvelope soapEnvelope = this.handleRESTUrlPost(contentTypeHeader); msgContext.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, request.getPipe()); processNonEntityEnclosingRESTHandler(soapEnvelope, msgContext, injectToAxis2Engine); return; } else { String soapAction = request.getHeaders().get(SOAP_ACTION_HEADER); int soapVersion = HTTPTransportUtils.initializeMessageContext(msgContext, soapAction, request.getUri(), contentTypeHeader); SOAPEnvelope envelope; if (soapVersion == 1) { SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); envelope = fac.getDefaultEnvelope(); } else if (soapVersion == 2) { SOAPFactory fac = OMAbstractFactory.getSOAP12Factory(); envelope = fac.getDefaultEnvelope(); } else { SOAPFactory fac = OMAbstractFactory.getSOAP12Factory(); envelope = fac.getDefaultEnvelope(); } if ((soapAction != null) && soapAction.startsWith("\"") && soapAction.endsWith("\"")) { soapAction = soapAction.substring(1, soapAction.length() - 1); msgContext.setSoapAction(soapAction); } msgContext.setEnvelope(envelope); } msgContext.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, request.getPipe()); if (injectToAxis2Engine) { AxisEngine.receive(msgContext); } } catch (AxisFault axisFault) { handleException("Error processing " + request.getMethod() + " request for : " + request.getUri(), axisFault); } catch (Exception e) { handleException("Error processing " + request.getMethod() + " reguest for : " + request.getUri() + ". Error detail: " + e.getMessage() + ". ", e); } }
From source file:org.apache.synapse.transport.passthru.TargetRequest.java
public void start(NHttpClientConnection conn) throws IOException, HttpException { if (pipe != null) { TargetContext.get(conn).setWriter(pipe); }/*from w w w . j a va 2 s. co m*/ String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString() : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : ""); long contentLength = -1; String contentLengthHeader = null; if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) { contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first(); } if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader); headers.remove(HTTP.CONTENT_LEN); } MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx(); if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) { contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH); } //fix for POST_TO_URI if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) { path = url.toString(); } //fix GET request empty body if ((("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))) { hasEntityBody = false; MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx); OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx); if (formatter != null && format != null) { URL _url = formatter.getTargetAddress(requestMsgCtx, format, url); if (_url != null && !_url.toString().isEmpty()) { if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString() .equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) { path = _url.toString(); } else { path = _url.getPath() + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery()) : ""); } } headers.remove(HTTP.CONTENT_TYPE); } } Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS); if (o != null && o instanceof TreeMap) { Map _headers = (Map) o; String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE); if (trpContentType != null && !trpContentType.equals("")) { if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) { addHeader(HTTP.CONTENT_TYPE, trpContentType); } } } if (hasEntityBody) { request = new BasicHttpEntityEnclosingRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1); BasicHttpEntity entity = new BasicHttpEntity(); boolean forceContentLength = requestMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH); boolean forceContentLengthCopy = requestMsgCtx .isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING); if (forceContentLength) { entity.setChunked(false); if (forceContentLengthCopy && contentLength > 0) { entity.setContentLength(contentLength); } } else { if (contentLength != -1) { entity.setChunked(false); entity.setContentLength(contentLength); } else { entity.setChunked(chunk); } } ((BasicHttpEntityEnclosingRequest) request).setEntity(entity); } else { request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1); } Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet(); for (Map.Entry<String, TreeSet<String>> entry : entries) { if (entry.getKey() != null) { Iterator<String> i = entry.getValue().iterator(); while (i.hasNext()) { request.addHeader(entry.getKey(), i.next()); } } } //setup wsa action.. if (request != null) { String soapAction = requestMsgCtx.getSoapAction(); if (soapAction == null) { soapAction = requestMsgCtx.getWSAAction(); } if (soapAction == null) { requestMsgCtx.getAxisOperation().getInputAction(); } if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) { Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION); if (existingHeader != null) { request.removeHeader(existingHeader); } MessageFormatter messageFormatter = MessageFormatterDecoratorFactory .createMessageFormatterDecorator(requestMsgCtx); request.setHeader(HTTPConstants.HEADER_SOAP_ACTION, messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction)); //request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO"); } } request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams())); //Chucking is not performed for request has "http 1.0" and "GET" http method if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)) || (("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))))) { this.processChunking(conn, requestMsgCtx); } if (!keepAlive) { request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } // Pre-process HTTP request conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn); conn.getContext().setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port)); conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request); // start the request targetConfiguration.getHttpProcessor().process(request, conn.getContext()); if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null && !route.isTunnelled()) { targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, conn.getContext()); } conn.submitRequest(request); if (hasEntityBody) { TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD); } else { TargetContext.updateState(conn, ProtocolState.REQUEST_DONE); } }
From source file:org.apache.synapse.transport.passthru.TargetRequest.java
public void addHeader(String name, String value) { if (headers.get(name) == null) { TreeSet<String> values = new TreeSet<String>(); values.add(value);/* w ww. jav a2s . com*/ if (HTTP.CONTENT_TYPE.equalsIgnoreCase(name)) { headers.put(HTTP.CONTENT_TYPE, values); } else { headers.put(name, values); } } else { if (HTTP.CONTENT_TYPE.equalsIgnoreCase(name)) { headers.remove(HTTP.CONTENT_TYPE); TreeSet<String> values = new TreeSet<String>(); values.add(value); headers.put(HTTP.CONTENT_TYPE, values); } else { TreeSet<String> values = headers.get(name); values.add(value); } } }
From source file:org.apache.synapse.transport.passthru.util.PassThroughTransportUtils.java
/** * Remove unwanted headers from the given header map. * * @param headers http header map * @param targetConfiguration configurations for the passThrough transporter *///w ww .j av a 2 s .com private static void removeUnwantedHeadersFromHeaderMap(Map headers, TargetConfiguration targetConfiguration) { Iterator iter = headers.keySet().iterator(); while (iter.hasNext()) { String headerName = (String) iter.next(); if (HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName) || HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) { iter.remove(); } if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(headerName) && !targetConfiguration.isPreserveHttpHeader(HTTP.CONN_KEEP_ALIVE)) { iter.remove(); } if (HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) && !targetConfiguration.isPreserveHttpHeader(HTTP.CONTENT_LEN)) { iter.remove(); } if (HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName) && !targetConfiguration.isPreserveHttpHeader(HTTP.CONTENT_TYPE)) { iter.remove(); } if (HTTP.DATE_HEADER.equalsIgnoreCase(headerName) && !targetConfiguration.isPreserveHttpHeader(HTTP.DATE_HEADER)) { iter.remove(); } if (HTTP.SERVER_HEADER.equalsIgnoreCase(headerName) && !targetConfiguration.isPreserveHttpHeader(HTTP.SERVER_HEADER)) { iter.remove(); } if (HTTP.USER_AGENT.equalsIgnoreCase(headerName) && !targetConfiguration.isPreserveHttpHeader(HTTP.USER_AGENT)) { iter.remove(); } } }
From source file:org.apache.synapse.transport.passthru.util.SourceResponseFactory.java
public static SourceResponse create(MessageContext msgContext, SourceRequest sourceRequest, SourceConfiguration sourceConfiguration) { // determine the status code to be sent int statusCode = PassThroughTransportUtils.determineHttpStatusCode(msgContext); SourceResponse sourceResponse;/*w ww. j a v a2 s. c om*/ String statusLine = PassThroughTransportUtils.determineHttpStatusLine(msgContext); if (msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_SC) != null && statusCode == ((Integer) msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_SC))) { sourceResponse = new SourceResponse(sourceConfiguration, statusCode, statusLine, sourceRequest); } else { if (msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_REASON_PHRASE) != null && (statusLine .equals(msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_REASON_PHRASE)))) { sourceResponse = new SourceResponse(sourceConfiguration, statusCode, sourceRequest); } else { sourceResponse = new SourceResponse(sourceConfiguration, statusCode, statusLine, sourceRequest); } } // set any transport headers Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH); boolean forceContentLengthCopy = msgContext .isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING); if (forceContentLength && forceContentLengthCopy && msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH) != null) { sourceResponse.addHeader(HTTP.CONTENT_LEN, (String) msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH)); } // When invoking http HEAD request esb set content length as 0 to response header. Since there is no message // body content length cannot be calculated inside synapse. Hence content length of the backend response is // set to sourceResponse. if (sourceRequest != null && PassThroughConstants.HTTP_HEAD .equalsIgnoreCase(sourceRequest.getRequest().getRequestLine().getMethod()) && msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH) != null) { sourceResponse.addHeader(PassThroughConstants.ORGINAL_CONTEN_LENGTH, (String) msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH)); } if (transportHeaders != null && msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) != null) { if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE) != null && msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE).toString() .contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) { transportHeaders.put(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED); } else { Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null && !Boolean.TRUE .equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) { transportHeaders.put(HTTP.CONTENT_TYPE, msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE)); } } } if (transportHeaders != null) { addResponseHeader(sourceResponse, transportHeaders); } else { Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY); if (noEntityBody == null || Boolean.FALSE == noEntityBody) { OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext); transportHeaders = new HashMap(); MessageFormatter messageFormatter = MessageFormatterDecoratorFactory .createMessageFormatterDecorator(msgContext); if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) == null) { transportHeaders.put(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction())); } addResponseHeader(sourceResponse, transportHeaders); } } // Add excess response header. String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS; Map excessHeaders = (Map) msgContext.getProperty(excessProp); if (excessHeaders != null) { for (Iterator iterator = excessHeaders.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); for (String excessVal : (Collection<String>) excessHeaders.get(key)) { sourceResponse.addHeader(key, (String) excessVal); } } } // keep alive String noKeepAlie = (String) msgContext.getProperty(PassThroughConstants.NO_KEEPALIVE); if ("true".equals(noKeepAlie)) { sourceResponse.setKeepAlive(false); } else { // If the payload is delayed for GET/HEAD/DELETE, http-core-nio will start processing request, without // waiting for the payload. Therefore the delayed payload will be appended to the next request. To avoid // that, disable keep-alive to avoid re-using the existing connection by client for the next request. if (sourceRequest != null) { String requestMethod = sourceRequest.getRequest().getRequestLine().getMethod(); if (requestMethod != null && isPayloadOptionalMethod(requestMethod.toUpperCase()) && (sourceRequest.getHeaders().containsKey(HTTP.CONTENT_LEN) || sourceRequest.getHeaders().containsKey(HTTP.TRANSFER_ENCODING))) { if (log.isDebugEnabled()) { log.debug("Disable keep-alive in the client connection : Content-length/Transfer-encoding" + " headers present for GET/HEAD/DELETE request"); } sourceResponse.setKeepAlive(false); } } } return sourceResponse; }
From source file:org.apache.synapse.transport.passthru.util.TargetRequestFactory.java
public static TargetRequest create(MessageContext msgContext, HttpRoute route, TargetConfiguration configuration) throws AxisFault { try {/*from w w w . j a v a2 s . c om*/ String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD); if (httpMethod == null) { httpMethod = "POST"; } // basic request Boolean noEntityBody = (Boolean) msgContext.getProperty(PassThroughConstants.NO_ENTITY_BODY); if (msgContext.getEnvelope().getBody().getFirstElement() != null) { noEntityBody = false; } EndpointReference epr = PassThroughTransportUtils.getDestinationEPR(msgContext); URL url = new URL(epr.getAddress()); TargetRequest request = new TargetRequest(configuration, route, url, httpMethod, noEntityBody == null || !noEntityBody); // headers PassThroughTransportUtils.removeUnwantedHeaders(msgContext, configuration); Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (o != null && o instanceof Map) { Map headers = (Map) o; for (Object entryObj : headers.entrySet()) { Map.Entry entry = (Map.Entry) entryObj; if (entry.getValue() != null && entry.getKey() instanceof String && entry.getValue() instanceof String) { if (HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) entry.getKey()) && !configuration.isPreserveHttpHeader(HTTPConstants.HEADER_HOST)) { if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) { request.addHeader((String) entry.getKey(), (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER)); } } else { request.addHeader((String) entry.getKey(), (String) entry.getValue()); } } } } String cType = getContentType(msgContext); if (cType != null && (!httpMethod.equals("GET") && !httpMethod.equals("DELETE"))) { String messageType = (String) msgContext.getProperty("messageType"); if (messageType != null) { boolean builderInvoked = false; final Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null) { builderInvoked = Boolean.TRUE .equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED)); } // if multipart related message type and unless if message // not get build we should // skip of setting formatter specific content Type if (messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED) == -1 && messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_FORM_DATA) == -1) { Map msgCtxheaders = (Map) o; if (msgCtxheaders != null && !cType.isEmpty()) { msgCtxheaders.put(HTTP.CONTENT_TYPE, cType); } request.addHeader(HTTP.CONTENT_TYPE, cType); } // if messageType is related to multipart and if message // already built we need to set new // boundary related content type at Content-Type header if (builderInvoked && (((messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED) != -1) || (messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_FORM_DATA) != -1)))) { request.addHeader(HTTP.CONTENT_TYPE, cType); } } else { request.addHeader(HTTP.CONTENT_TYPE, cType); } } // version String forceHttp10 = (String) msgContext.getProperty(PassThroughConstants.FORCE_HTTP_1_0); if ("true".equals(forceHttp10)) { request.setVersion(HttpVersion.HTTP_1_0); } // keep alive String noKeepAlie = (String) msgContext.getProperty(PassThroughConstants.NO_KEEPALIVE); if ("true".equals(noKeepAlie)) { request.setKeepAlive(false); } // port int port = url.getPort(); if (port == -1) { request.setPort(request.getRoute().getTargetHost().getPort()); } else { request.setPort(port); } // chunk String disableChunking = (String) msgContext.getProperty(PassThroughConstants.DISABLE_CHUNKING); if ("true".equals(disableChunking)) { request.setChunk(false); } // full url String fullUrl = (String) msgContext.getProperty(PassThroughConstants.FULL_URI); if ("true".equals(fullUrl)) { request.setFullUrl(true); } // Add excess respsonse header. String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS; Map excessHeaders = (Map) msgContext.getProperty(excessProp); if (excessHeaders != null) { for (Iterator iterator = excessHeaders.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); for (String excessVal : (Collection<String>) excessHeaders.get(key)) { request.addHeader(key, (String) excessVal); } } } return request; } catch (MalformedURLException e) { handleException("Invalid to address" + msgContext.getTo().getAddress(), e); } return null; }
From source file:org.digitalcampus.oppia.monitor.task.LoginTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];/* w w w. java 2 s . c o m*/ User u = (User) payload.getData().get(0); HTTPConnectionUtils client = new HTTPConnectionUtils(ctx); String url = prefs.getString("prefServer", ctx.getString(R.string.prefServerDefault)) + OppiaMonitor.LOGIN_PATH; JSONObject json = new JSONObject(); HttpPost httpPost = new HttpPost(url); try { // update progress dialog publishProgress(ctx.getString(R.string.login_process)); Log.d(TAG, "logging in ...." + u.getUsername()); // add post params json.put("username", u.getUsername()); json.put("password", u.getPassword()); StringEntity se = new StringEntity(json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(se); // make request HttpResponse response = client.execute(httpPost); // read response InputStream content = response.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content), 4096); String responseStr = ""; String s = ""; while ((s = buffer.readLine()) != null) { responseStr += s; } // check status code switch (response.getStatusLine().getStatusCode()) { case 400: // unauthorised payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_login)); break; case 201: // logged in JSONObject jsonResp = new JSONObject(responseStr); u.setApi_key(jsonResp.getString("api_key")); u.setFirstname(jsonResp.getString("first_name")); u.setLastname(jsonResp.getString("last_name")); payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.login_complete)); break; default: Log.d(TAG, responseStr); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (ClientProtocolException e) { e.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (IOException e) { e.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (JSONException e) { BugSenseHandler.sendException(e); e.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_processing_response)); } finally { } return payload; }
From source file:org.digitalcampus.oppia.task.LoginTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];// w ww . j a va 2s . co m User u = (User) payload.getData().get(0); // firstly try to login locally DbHelper db0 = new DbHelper(ctx); try { User localUser = db0.getUser(u.getUsername()); Log.d(TAG, "logged pw: " + localUser.getPasswordEncrypted()); Log.d(TAG, "entered pw: " + u.getPasswordEncrypted()); if (localUser.getPasswordEncrypted().equals(u.getPasswordEncrypted())) { payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.login_complete)); return payload; } } catch (UserNotFoundException unfe) { // Just ignore - means that user isn't already registered on the device } DatabaseManager.getInstance().closeDatabase(); HTTPConnectionUtils client = new HTTPConnectionUtils(ctx); String url = prefs.getString(PrefsActivity.PREF_SERVER, ctx.getString(R.string.prefServerDefault)) + MobileLearning.LOGIN_PATH; JSONObject json = new JSONObject(); HttpPost httpPost = new HttpPost(url); try { // update progress dialog publishProgress(ctx.getString(R.string.login_process)); // add post params json.put("username", u.getUsername()); json.put("password", u.getPassword()); StringEntity se = new StringEntity(json.toString(), "utf8"); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(se); // make request HttpResponse response = client.execute(httpPost); // read response InputStream content = response.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content), 4096); String responseStr = ""; String s = ""; while ((s = buffer.readLine()) != null) { responseStr += s; } // check status code switch (response.getStatusLine().getStatusCode()) { case 400: // unauthorised payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_login)); break; case 201: // logged in JSONObject jsonResp = new JSONObject(responseStr); u.setApiKey(jsonResp.getString("api_key")); u.setFirstname(jsonResp.getString("first_name")); u.setLastname(jsonResp.getString("last_name")); try { u.setPoints(jsonResp.getInt("points")); u.setBadges(jsonResp.getInt("badges")); } catch (JSONException e) { u.setPoints(0); u.setBadges(0); } try { u.setScoringEnabled(jsonResp.getBoolean("scoring")); u.setBadgingEnabled(jsonResp.getBoolean("badging")); } catch (JSONException e) { u.setScoringEnabled(true); u.setBadgingEnabled(true); } try { JSONObject metadata = jsonResp.getJSONObject("metadata"); MetaDataUtils mu = new MetaDataUtils(ctx); mu.saveMetaData(metadata, prefs); } catch (JSONException e) { e.printStackTrace(); } DbHelper db = new DbHelper(ctx); db.addOrUpdateUser(u); DatabaseManager.getInstance().closeDatabase(); payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.login_complete)); break; default: payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } } catch (UnsupportedEncodingException e) { payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (ClientProtocolException e) { payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (IOException e) { payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (JSONException e) { Mint.logException(e); e.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_processing_response)); } return payload; }
From source file:org.digitalcampus.oppia.task.RegisterTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];// ww w . j a v a 2 s .c o m User u = (User) payload.getData().get(0); HTTPConnectionUtils client = new HTTPConnectionUtils(ctx); String url = prefs.getString(PrefsActivity.PREF_SERVER, ctx.getString(R.string.prefServerDefault)) + MobileLearning.REGISTER_PATH; HttpPost httpPost = new HttpPost(url); try { // update progress dialog publishProgress(ctx.getString(R.string.register_process)); // add post params JSONObject json = new JSONObject(); json.put("username", u.getUsername()); json.put("password", u.getPassword()); json.put("passwordagain", u.getPasswordAgain()); json.put("email", u.getEmail()); json.put("firstname", u.getFirstname()); json.put("lastname", u.getLastname()); json.put("jobtitle", u.getJobTitle()); json.put("organisation", u.getOrganisation()); json.put("phoneno", u.getPhoneNo()); StringEntity se = new StringEntity(json.toString(), "utf8"); //Log.d("data",se.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(se); // make request HttpResponse response = client.execute(httpPost); // read response InputStream content = response.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content), 4096); String responseStr = ""; String s = ""; while ((s = buffer.readLine()) != null) { responseStr += s; } switch (response.getStatusLine().getStatusCode()) { case 400: // unauthorised payload.setResult(false); payload.setResultResponse(responseStr); break; case 201: // logged in JSONObject jsonResp = new JSONObject(responseStr); u.setApiKey(jsonResp.getString("api_key")); try { u.setPoints(jsonResp.getInt("points")); u.setBadges(jsonResp.getInt("badges")); } catch (JSONException e) { u.setPoints(0); u.setBadges(0); } try { u.setScoringEnabled(jsonResp.getBoolean("scoring")); u.setBadgingEnabled(jsonResp.getBoolean("badging")); } catch (JSONException e) { u.setScoringEnabled(true); u.setBadgingEnabled(true); } try { JSONObject metadata = jsonResp.getJSONObject("metadata"); MetaDataUtils mu = new MetaDataUtils(ctx); mu.saveMetaData(metadata, prefs); } catch (JSONException e) { e.printStackTrace(); } u.setFirstname(jsonResp.getString("first_name")); u.setLastname(jsonResp.getString("last_name")); // add or update user in db DbHelper db = new DbHelper(ctx); db.addOrUpdateUser(u); DatabaseManager.getInstance().closeDatabase(); payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.register_complete)); break; default: payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } } catch (UnsupportedEncodingException e) { payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (ClientProtocolException e) { payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (IOException e) { payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (JSONException e) { Mint.logException(e); e.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_processing_response)); } return payload; }