List of usage examples for org.apache.http.protocol HTTP CONTENT_LEN
String CONTENT_LEN
To view the source code for org.apache.http.protocol HTTP CONTENT_LEN.
Click Source Link
From source file:com.scvngr.levelup.core.net.LevelUpRequest.java
@Override @NonNull//from w ww .j a v a 2 s . co m public final Map<String, String> getRequestHeaders(@NonNull final Context context) { final Map<String, String> headers; final HashMap<String, String> temp = new HashMap<String, String>(super.getRequestHeaders(context)); final RequestBody body = mBody; if (null != body) { temp.put(HTTP.CONTENT_TYPE, body.getContentType()); temp.put(HTTP.CONTENT_LEN, String.valueOf(body.getContentLength())); } else { temp.put(HTTP.CONTENT_TYPE, RequestUtils.HEADER_CONTENT_TYPE_JSON); } temp.put(HEADER_LEVELUP_API_KEY, context.getString(R.string.levelup_api_key)); final AccessToken token = getAccessToken(context); if (null != token) { temp.put(HEADER_AUTHORIZATION, String.format(Locale.US, AUTH_TOKEN_TYPE_FORMAT, token.getAccessToken())); } headers = NullUtils.nonNullContract(Collections.unmodifiableMap(temp)); return headers; }
From source file:com.microsoft.live.unittest.ApiTest.java
License:asdf
/** Loads an invalid formated body into the HttpClient * @throws Exception *///from w w w . j av a2 s . c o m protected void loadInvalidResponseBody() throws Exception { byte[] bytes = INVALID_FORMAT.getBytes(); this.mockResponse.addHeader(HTTP.CONTENT_LEN, Long.toString(bytes.length)); this.mockEntity.setInputStream(new ByteArrayInputStream(bytes)); this.mockClient.setHttpResponse(mockResponse); }
From source file:edu.ucsb.eucalyptus.transport.query.WalrusQueryDispatcher.java
public String getOperation(HttpRequest httpRequest, MessageContext messageContext) throws EucalyptusCloudException { //Figure out if it is an operation on the service, a bucket or an object Map operationParams = new HashMap(); String[] target = null;// w w w . j ava2 s . co m String path = httpRequest.getOperationPath(); boolean walrusInternalOperation = false; if (path.length() > 0) { target = getTarget(path); } String verb = httpRequest.getHttpMethod(); Map<String, String> headers = httpRequest.getHeaders(); CaseInsensitiveMap caseInsensitiveHeaders = new CaseInsensitiveMap(headers); String operationKey = ""; Map<String, String> params = httpRequest.getParameters(); String operationName = null; long contentLength = 0; String contentLengthString = (String) messageContext.getProperty(HTTP.CONTENT_LEN); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } if (caseInsensitiveHeaders.containsKey(StorageProperties.EUCALYPTUS_OPERATION)) { String value = caseInsensitiveHeaders.get(StorageProperties.EUCALYPTUS_OPERATION); for (WalrusProperties.WalrusInternalOperations operation : WalrusProperties.WalrusInternalOperations .values()) { if (value.toLowerCase().equals(operation.toString().toLowerCase())) { operationName = operation.toString(); walrusInternalOperation = true; break; } } if (!walrusInternalOperation) { for (WalrusProperties.StorageOperations operation : WalrusProperties.StorageOperations.values()) { if (value.toLowerCase().equals(operation.toString().toLowerCase())) { operationName = operation.toString(); walrusInternalOperation = true; break; } } } } if (target == null) { //target = service operationKey = SERVICE + verb; } else if (target.length < 2) { //target = bucket if (!target[0].equals("")) { operationKey = BUCKET + verb; operationParams.put("Bucket", target[0]); if (verb.equals(HTTPVerb.POST.toString())) { InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); messageContext.setProperty(WalrusProperties.STREAMING_HTTP_PUT, Boolean.TRUE); String contentType = caseInsensitiveHeaders.get(HTTP.CONTENT_TYPE); int postContentLength = Integer.parseInt(caseInsensitiveHeaders.get(HTTP.CONTENT_LEN)); POSTRequestContext postRequestContext = new POSTRequestContext(in, contentType, postContentLength); FileUpload fileUpload = new FileUpload(new WalrusFileItemFactory()); InputStream formDataIn = null; String objectKey = null; String file = ""; String key; Map<String, String> formFields = new HashMap<String, String>(); try { List<FileItem> parts = fileUpload.parseRequest(postRequestContext); for (FileItem part : parts) { if (part.isFormField()) { String fieldName = part.getFieldName().toString().toLowerCase(); InputStream formFieldIn = part.getInputStream(); int bytesRead; String fieldValue = ""; byte[] bytes = new byte[512]; while ((bytesRead = formFieldIn.read(bytes)) > 0) { fieldValue += new String(bytes, 0, bytesRead); } formFields.put(fieldName, fieldValue); } else { formDataIn = part.getInputStream(); if (part.getName() != null) file = part.getName(); } } } catch (Exception ex) { LOG.warn(ex, ex); throw new EucalyptusCloudException("could not process form request"); } String authenticationHeader = ""; formFields.put(WalrusProperties.FormField.bucket.toString(), target[0]); if (formFields.containsKey(WalrusProperties.FormField.key.toString())) { objectKey = formFields.get(WalrusProperties.FormField.key.toString()); objectKey = objectKey.replaceAll("\\$\\{filename\\}", file); } if (formFields.containsKey(WalrusProperties.FormField.acl.toString())) { String acl = formFields.get(WalrusProperties.FormField.acl.toString()); headers.put(WalrusProperties.AMZ_ACL, acl); } if (formFields.containsKey(WalrusProperties.FormField.success_action_redirect.toString())) { String successActionRedirect = formFields .get(WalrusProperties.FormField.success_action_redirect.toString()); operationParams.put("SuccessActionRedirect", successActionRedirect); } if (formFields.containsKey(WalrusProperties.FormField.success_action_status.toString())) { Integer successActionStatus = Integer.parseInt( formFields.get(WalrusProperties.FormField.success_action_status.toString())); if (successActionStatus == 200 || successActionStatus == 201) operationParams.put("SuccessActionStatus", successActionStatus); else operationParams.put("SuccessActionStatus", 204); } else { operationParams.put("SuccessActionStatus", 204); } if (formFields.containsKey(WalrusProperties.FormField.policy.toString())) { String policy = new String( Base64.decode(formFields.remove(WalrusProperties.FormField.policy.toString()))); String policyData; try { policyData = new String(Base64.encode(policy.getBytes())); } catch (Exception ex) { LOG.warn(ex, ex); throw new EucalyptusCloudException("error reading policy data."); } //parse policy try { JSONObject policyObject = new JSONObject(policy); String expiration = (String) policyObject .get(WalrusProperties.PolicyHeaders.expiration.toString()); if (expiration != null) { Date expirationDate = DateUtils.parseIso8601DateTimeOrDate(expiration); if ((new Date()).getTime() > expirationDate.getTime()) { LOG.warn("Policy has expired."); //TODO: currently this will be reported as an invalid operation //Fix this to report a security exception throw new EucalyptusCloudException("Policy has expired."); } } List<String> policyItemNames = new ArrayList<String>(); JSONArray conditions = (JSONArray) policyObject .get(WalrusProperties.PolicyHeaders.conditions.toString()); for (int i = 0; i < conditions.length(); ++i) { Object policyItem = conditions.get(i); if (policyItem instanceof JSONObject) { JSONObject jsonObject = (JSONObject) policyItem; if (!exactMatch(jsonObject, formFields, policyItemNames)) { LOG.warn("Policy verification failed. "); throw new EucalyptusCloudException("Policy verification failed."); } } else if (policyItem instanceof JSONArray) { JSONArray jsonArray = (JSONArray) policyItem; if (!partialMatch(jsonArray, formFields, policyItemNames)) { LOG.warn("Policy verification failed. "); throw new EucalyptusCloudException("Policy verification failed."); } } } Set<String> formFieldsKeys = formFields.keySet(); for (String formKey : formFieldsKeys) { if (formKey.startsWith(WalrusProperties.IGNORE_PREFIX)) continue; boolean fieldOkay = false; for (WalrusProperties.IgnoredFields field : WalrusProperties.IgnoredFields .values()) { if (formKey.equals(field.toString().toLowerCase())) { fieldOkay = true; break; } } if (fieldOkay) continue; if (policyItemNames.contains(formKey)) continue; LOG.warn("All fields except those marked with x-ignore- should be in policy."); throw new EucalyptusCloudException( "All fields except those marked with x-ignore- should be in policy."); } } catch (Exception ex) { //rethrow if (ex instanceof EucalyptusCloudException) throw (EucalyptusCloudException) ex; LOG.warn(ex); } //all form uploads without a policy are anonymous if (formFields .containsKey(WalrusProperties.FormField.AWSAccessKeyId.toString().toLowerCase())) { String accessKeyId = formFields .remove(WalrusProperties.FormField.AWSAccessKeyId.toString().toLowerCase()); authenticationHeader += "AWS" + " " + accessKeyId + ":"; } if (formFields.containsKey(WalrusProperties.FormField.signature.toString())) { String signature = formFields.remove(WalrusProperties.FormField.signature.toString()); authenticationHeader += signature; headers.put(HMACQuerySecurityHandler.SecurityParameter.Authorization.toString(), authenticationHeader); } headers.put(WalrusProperties.FormField.FormUploadPolicyData.toString(), policyData); } operationParams.put("Key", objectKey); key = target[0] + "." + objectKey; String randomKey = key + "." + Hashes.getRandom(10); LinkedBlockingQueue<WalrusDataMessage> putQueue = getWriteMessenger() .interruptAllAndGetQueue(key, randomKey); Writer writer = new Writer(formDataIn, postContentLength, putQueue); writer.start(); operationParams.put("ContentLength", (new Long(postContentLength).toString())); operationParams.put(WalrusProperties.Headers.RandomKey.toString(), randomKey); } } else { operationKey = SERVICE + verb; } } else { //target = object operationKey = OBJECT + verb; String objectKey = ""; String splitOn = ""; for (int i = 1; i < target.length; ++i) { objectKey += splitOn + target[i]; splitOn = "/"; } operationParams.put("Bucket", target[0]); operationParams.put("Key", objectKey); if (!params.containsKey(OperationParameter.acl.toString())) { if (verb.equals(HTTPVerb.PUT.toString())) { if (caseInsensitiveHeaders.containsKey(WalrusProperties.COPY_SOURCE.toString())) { String copySource = caseInsensitiveHeaders.get(WalrusProperties.COPY_SOURCE.toString()); String[] sourceTarget = getTarget(copySource); String sourceObjectKey = ""; String sourceSplitOn = ""; if (sourceTarget.length > 1) { for (int i = 1; i < sourceTarget.length; ++i) { sourceObjectKey += sourceSplitOn + sourceTarget[i]; sourceSplitOn = "/"; } operationParams.put("SourceBucket", sourceTarget[0]); operationParams.put("SourceObject", sourceObjectKey); operationParams.put("DestinationBucket", operationParams.remove("Bucket")); operationParams.put("DestinationObject", operationParams.remove("Key")); String metaDataDirective = caseInsensitiveHeaders .get(WalrusProperties.METADATA_DIRECTIVE.toString()); if (metaDataDirective != null) { operationParams.put("MetadataDirective", metaDataDirective); } AccessControlListType accessControlList; if (contentLength > 0) { InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); accessControlList = getAccessControlList(in); } else { accessControlList = new AccessControlListType(); } operationParams.put("AccessControlList", accessControlList); operationKey += WalrusProperties.COPY_SOURCE.toString(); Iterator<String> iterator = caseInsensitiveHeaders.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); for (WalrusProperties.CopyHeaders header : WalrusProperties.CopyHeaders.values()) { if (key.replaceAll("-", "").equals(header.toString().toLowerCase())) { String value = caseInsensitiveHeaders.get(key); parseExtendedHeaders(operationParams, header.toString(), value); } } } } else { throw new EucalyptusCloudException("Malformed COPY request"); } } else { messageContext.setProperty(WalrusProperties.STREAMING_HTTP_PUT, Boolean.TRUE); InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); InputStream inStream = in; if ((!walrusInternalOperation) || (!WalrusProperties.StorageOperations.StoreSnapshot .toString().equals(operationName))) { inStream = new BufferedInputStream(in); } else { try { inStream = new GZIPInputStream(in); } catch (Exception ex) { LOG.warn(ex, ex); throw new EucalyptusCloudException("cannot process input"); } } String key = target[0] + "." + objectKey; String randomKey = key + "." + Hashes.getRandom(10); LinkedBlockingQueue<WalrusDataMessage> putQueue = getWriteMessenger() .interruptAllAndGetQueue(key, randomKey); Writer writer = new Writer(inStream, contentLength, putQueue); writer.start(); operationParams.put("ContentLength", (new Long(contentLength).toString())); operationParams.put(WalrusProperties.Headers.RandomKey.toString(), randomKey); } } else if (verb.equals(HTTPVerb.GET.toString())) { messageContext.setProperty(WalrusProperties.STREAMING_HTTP_GET, Boolean.TRUE); if (!walrusInternalOperation) { operationParams.put("GetData", Boolean.TRUE); operationParams.put("InlineData", Boolean.FALSE); operationParams.put("GetMetaData", Boolean.TRUE); Iterator<String> iterator = caseInsensitiveHeaders.keySet().iterator(); boolean isExtendedGet = false; while (iterator.hasNext()) { String key = iterator.next(); for (WalrusProperties.ExtendedGetHeaders header : WalrusProperties.ExtendedGetHeaders .values()) { if (key.replaceAll("-", "").equals(header.toString().toLowerCase())) { String value = caseInsensitiveHeaders.get(key); isExtendedGet = true; parseExtendedHeaders(operationParams, header.toString(), value); } } } if (isExtendedGet) { operationKey += "extended"; //only supported through SOAP operationParams.put("ReturnCompleteObjectOnConditionFailure", Boolean.FALSE); } } else { for (WalrusProperties.InfoOperations operation : WalrusProperties.InfoOperations.values()) { if (operation.toString().equals(operationName)) { messageContext.removeProperty(WalrusProperties.STREAMING_HTTP_GET); break; } } } if (params.containsKey(WalrusProperties.GetOptionalParameters.IsCompressed.toString())) { Boolean isCompressed = Boolean.parseBoolean( params.remove(WalrusProperties.GetOptionalParameters.IsCompressed.toString())); operationParams.put("IsCompressed", isCompressed); } } else if (verb.equals(HTTPVerb.HEAD.toString())) { messageContext.setProperty(WalrusProperties.STREAMING_HTTP_GET, Boolean.FALSE); if (!walrusInternalOperation) { operationParams.put("GetData", Boolean.FALSE); operationParams.put("InlineData", Boolean.FALSE); operationParams.put("GetMetaData", Boolean.TRUE); } } } } if (verb.equals(HTTPVerb.PUT.toString()) && params.containsKey(OperationParameter.acl.toString())) { //read ACL InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); operationParams.put("AccessControlPolicy", getAccessControlPolicy(in)); } ArrayList paramsToRemove = new ArrayList(); boolean addMore = true; Iterator iterator = params.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); String keyString = key.toString().toLowerCase(); boolean dontIncludeParam = false; for (HMACQuerySecurityHandler.SecurityParameter securityParam : HMACQuerySecurityHandler.SecurityParameter .values()) { if (keyString.equals(securityParam.toString().toLowerCase())) { dontIncludeParam = true; break; } } if (dontIncludeParam) continue; String value = params.get(key); if (value != null) { String[] keyStringParts = keyString.split("-"); if (keyStringParts.length > 1) { keyString = ""; for (int i = 0; i < keyStringParts.length; ++i) { keyString += toUpperFirst(keyStringParts[i]); } } else { keyString = toUpperFirst(keyString); } operationParams.put(keyString, value); } if (addMore) { //just add the first one to the key operationKey += keyString.toLowerCase(); addMore = false; } paramsToRemove.add(key); } for (Object key : paramsToRemove) { params.remove(key); } if (!walrusInternalOperation) { operationName = operationMap.get(operationKey); } httpRequest.setBindingArguments(operationParams); messageContext.setProperty(WalrusProperties.WALRUS_OPERATION, operationName); return operationName; }
From source file:com.microsoft.live.unittest.ApiTest.java
License:asdf
/** * Loads an invalid path response into the HttpClient. * * @param requestPath//from w ww. j a v a 2 s . co m * @throws Exception */ protected void loadPathInvalidResponse(String requestPath) throws Exception { JSONObject error = new JSONObject(); error.put(JsonKeys.CODE, ErrorCodes.REQUEST_URL_INVALID); String message = String.format(ErrorMessages.URL_NOT_VALID, requestPath.toLowerCase()); error.put(JsonKeys.MESSAGE, message); JSONObject response = new JSONObject(); response.put(JsonKeys.ERROR, error); byte[] bytes = response.toString().getBytes(); this.mockResponse.addHeader(HTTP.CONTENT_LEN, Long.toString(bytes.length)); this.mockEntity.setInputStream(new ByteArrayInputStream(bytes)); StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad Request"); this.mockResponse.setStatusLine(status); this.mockClient.setHttpResponse(this.mockResponse); }
From source file:com.ibm.og.client.ApacheClient.java
private CloseableHttpClient createClient() { final HttpClientBuilder builder = HttpClients.custom(); if (this.userAgent != null) { builder.setUserAgent(this.userAgent); }/*from w ww .j a va2 s. co m*/ // Some authentication implementations add Content-Length or Transfer-Encoding headers as a part // of their authentication algorithm; remove them here so that the default interceptors do not // throw a ProtocolException // @see RequestContent interceptor builder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONTENT_LEN); } }); return builder.setRequestExecutor(new HttpRequestExecutor(this.waitForContinue)) .setConnectionManager(createConnectionManager()) // TODO investigate ConnectionConfig, particularly bufferSize and fragmentSizeHint // TODO defaultCredentialsProvider and defaultAuthSchemeRegistry for pre/passive auth? .setConnectionReuseStrategy(createConnectionReuseStrategy()) .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE).disableConnectionState() .disableCookieManagement().disableContentCompression().disableAuthCaching() .setRetryHandler(new CustomHttpRequestRetryHandler(this.retryCount, this.requestSentRetry)) .setRedirectStrategy(new CustomRedirectStrategy()).setDefaultRequestConfig(createRequestConfig()) .evictExpiredConnections() .evictIdleConnections(Long.valueOf(this.maxIdleTime), TimeUnit.MILLISECONDS).build(); }
From source file:edu.ucsb.eucalyptus.transport.Axis2InOutMessageReceiver.java
public void invokeBusinessLogic(MessageContext msgContext, MessageContext newMsgContext) throws AxisFault { String methodName = this.findOperation(msgContext); Class serviceMethodArgType = this.findArgumentClass(methodName); SOAPFactory factory = this.getSOAPFactory(msgContext); OMElement msgBodyOm = msgContext.getEnvelope().getBody().getFirstElement(); String bindingName = this.findBindingName(msgBodyOm); EucalyptusMessage wrappedParam = this.bindMessage(methodName, serviceMethodArgType, msgBodyOm, bindingName); HttpRequest httprequest = (HttpRequest) msgContext.getProperty(GenericHttpDispatcher.HTTP_REQUEST); if (httprequest == null) { this.verifyUser(msgContext, wrappedParam); } else {// w w w.j a va2 s. co m bindingName = httprequest.getBindingName(); Policy p = new Policy(); newMsgContext.setProperty(RampartMessageData.KEY_RAMPART_POLICY, p); //:: fixes the handling of certain kinds of client brain damage ::// if (httprequest.isPureClient()) { if (wrappedParam instanceof ModifyImageAttributeType) { ModifyImageAttributeType pure = ((ModifyImageAttributeType) wrappedParam); pure.setImageId(purifyImageIn(pure.getImageId())); } else if (wrappedParam instanceof DescribeImageAttributeType) { DescribeImageAttributeType pure = ((DescribeImageAttributeType) wrappedParam); pure.setImageId(purifyImageIn(pure.getImageId())); } else if (wrappedParam instanceof ResetImageAttributeType) { ResetImageAttributeType pure = ((ResetImageAttributeType) wrappedParam); pure.setImageId(purifyImageIn(pure.getImageId())); } else if (wrappedParam instanceof DescribeImagesType) { ArrayList<String> strs = Lists.newArrayList(); for (String imgId : ((DescribeImagesType) wrappedParam).getImagesSet()) { strs.add(purifyImageIn(imgId)); } ((DescribeImagesType) wrappedParam).setImagesSet(strs); } else if (wrappedParam instanceof DeregisterImageType) { DeregisterImageType pure = ((DeregisterImageType) wrappedParam); pure.setImageId(purifyImageIn(pure.getImageId())); } else if (wrappedParam instanceof RunInstancesType) { RunInstancesType pure = ((RunInstancesType) wrappedParam); pure.setImageId(purifyImageIn(pure.getImageId())); pure.setKernelId(purifyImageIn(pure.getKernelId())); pure.setRamdiskId(purifyImageIn(pure.getRamdiskId())); } } } MuleMessage message = this.invokeService(methodName, wrappedParam); if (message == null) throw new AxisFault("Received a NULL response. This is a bug -- it should NEVER happen."); this.checkException(message); if (httprequest != null) { //:: fixes the handling of certain kinds of client brain damage ::// if (httprequest.isPureClient()) { if (message.getPayload() instanceof DescribeImagesResponseType) { DescribeImagesResponseType purify = (DescribeImagesResponseType) message.getPayload(); for (ImageDetails img : purify.getImagesSet()) { img.setImageId(img.getImageId().replaceFirst("^e", "a").toLowerCase()); if (img.getKernelId() != null) img.setKernelId(img.getKernelId().replaceFirst("^e", "a").toLowerCase()); if (img.getRamdiskId() != null) img.setRamdiskId(img.getRamdiskId().replaceFirst("^e", "a").toLowerCase()); } } else if (message.getPayload() instanceof DescribeInstancesResponseType) { DescribeInstancesResponseType purify = (DescribeInstancesResponseType) message.getPayload(); for (ReservationInfoType rsvInfo : purify.getReservationSet()) { for (RunningInstancesItemType r : rsvInfo.getInstancesSet()) { r.setImageId(r.getImageId().replaceFirst("^e", "a").toLowerCase()); if (r.getKernel() != null) r.setKernel(r.getKernel().replaceFirst("^e", "a").toLowerCase()); if (r.getRamdisk() != null) r.setRamdisk(r.getRamdisk().replaceFirst("^e", "a").toLowerCase()); } } } } } if (newMsgContext != null) { SOAPEnvelope envelope = generateMessage(methodName, factory, bindingName, message.getPayload(), httprequest == null ? null : httprequest.getOriginalNamespace()); newMsgContext.setEnvelope(envelope); } newMsgContext.setProperty(Axis2HttpWorker.REAL_HTTP_REQUEST, msgContext.getProperty(Axis2HttpWorker.REAL_HTTP_REQUEST)); newMsgContext.setProperty(Axis2HttpWorker.REAL_HTTP_RESPONSE, msgContext.getProperty(Axis2HttpWorker.REAL_HTTP_RESPONSE)); LOG.info("Returning reply: " + message.getPayload()); if (message.getPayload() instanceof WalrusErrorMessageType) { WalrusErrorMessageType errorMessage = (WalrusErrorMessageType) message.getPayload(); msgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, errorMessage.getHttpCode()); newMsgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, errorMessage.getHttpCode()); //This selects the data formatter newMsgContext.setProperty("messageType", "application/walrus"); return; } Boolean putType = (Boolean) msgContext.getProperty(WalrusProperties.STREAMING_HTTP_PUT); Boolean getType = (Boolean) msgContext.getProperty(WalrusProperties.STREAMING_HTTP_GET); if (getType != null || putType != null) { WalrusDataResponseType reply = (WalrusDataResponseType) message.getPayload(); AxisHttpResponse response = (AxisHttpResponse) msgContext .getProperty(Axis2HttpWorker.REAL_HTTP_RESPONSE); response.addHeader(new BasicHeader("Last-Modified", reply.getLastModified())); response.addHeader(new BasicHeader("ETag", '\"' + reply.getEtag() + '\"')); if (getType != null) { newMsgContext.setProperty(WalrusProperties.STREAMING_HTTP_GET, getType); WalrusDataRequestType request = (WalrusDataRequestType) wrappedParam; Boolean isCompressed = request.getIsCompressed(); if (isCompressed == null) isCompressed = false; if (isCompressed) { newMsgContext.setProperty("GET_COMPRESSED", isCompressed); } else { Long contentLength = reply.getSize(); response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, String.valueOf(contentLength))); } List<MetaDataEntry> metaData = reply.getMetaData(); for (MetaDataEntry metaDataEntry : metaData) { response.addHeader( new BasicHeader(WalrusProperties.AMZ_META_HEADER_PREFIX + metaDataEntry.getName(), metaDataEntry.getValue())); } if (getType.equals(Boolean.TRUE)) { newMsgContext.setProperty("GET_KEY", request.getBucket() + "." + request.getKey()); newMsgContext.setProperty("GET_RANDOM_KEY", request.getRandomKey()); } //This selects the data formatter newMsgContext.setProperty("messageType", "application/walrus"); } else if (putType != null) { if (reply instanceof PostObjectResponseType) { PostObjectResponseType postReply = (PostObjectResponseType) reply; String redirectUrl = postReply.getRedirectUrl(); if (redirectUrl != null) { response.addHeader(new BasicHeader("Location", redirectUrl)); msgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, HttpStatus.SC_SEE_OTHER); newMsgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, HttpStatus.SC_SEE_OTHER); newMsgContext.setProperty("messageType", "application/walrus"); } else { Integer successCode = postReply.getSuccessCode(); if (successCode != null) { newMsgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, successCode); if (successCode == 201) { return; } else { newMsgContext.setProperty("messageType", "application/walrus"); return; } } } } response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, String.valueOf(0))); } } }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSender.java
/** * Remove unwanted headers from the given header map. * * @param headers Header map/*from w w w . j a v a2 s .c om*/ * @param nHttpConfiguration NHttp transporter base configurations */ private void removeUnwantedHeadersFromHeaderMap(Map headers, NHttpConfiguration nHttpConfiguration) { Iterator iter = headers.keySet().iterator(); while (iter.hasNext()) { String headerName = (String) iter.next(); if (HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName) || HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName) || HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName) || HTTP.CONTENT_LEN.equalsIgnoreCase(headerName)) { iter.remove(); } if (HTTP.SERVER_HEADER.equalsIgnoreCase(headerName) && !nHttpConfiguration.isPreserveHttpHeader(HTTP.SERVER_HEADER)) { iter.remove(); } if (HTTP.USER_AGENT.equalsIgnoreCase(headerName) && !nHttpConfiguration.isPreserveHttpHeader(HTTP.USER_AGENT)) { iter.remove(); } if (HTTP.DATE_HEADER.equalsIgnoreCase(headerName) && !nHttpConfiguration.isPreserveHttpHeader(HTTP.DATE_HEADER)) { iter.remove(); } } }
From source file:org.apache.synapse.message.senders.blocking.BlockingMsgSenderUtils.java
private static boolean isSkipTransportHeader(String headerName) { return HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName) || HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName) || HTTP.DATE_HEADER.equalsIgnoreCase(headerName) || HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName) || HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) || HTTP.SERVER_HEADER.equalsIgnoreCase(headerName) || HTTP.USER_AGENT.equalsIgnoreCase(headerName) || "SOAPAction".equalsIgnoreCase(headerName); }