List of usage examples for com.google.common.net HttpHeaders CONTENT_TYPE
String CONTENT_TYPE
To view the source code for com.google.common.net HttpHeaders CONTENT_TYPE.
Click Source Link
From source file:org.jclouds.s3.filters.RequestAuthorizeSignatureV2.java
void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) { // note that we fall back to headers, and some requests such as ?uploads do not have a // payload, yet specify payload related parameters buffer.append(/*from w ww . j av a2 s . c o m*/ request.getPayload() == null ? Strings.nullToEmpty(request.getFirstHeaderOrNull("Content-MD5")) : HttpUtils.nullToEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata().getContentMD5())) .append("\n"); buffer.append(Strings .nullToEmpty(request.getPayload() == null ? request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE) : request.getPayload().getContentMetadata().getContentType())) .append("\n"); for (String header : FIRST_HEADERS_TO_SIGN) buffer.append(HttpUtils.nullToEmpty(request.getHeaders().get(header))).append("\n"); }
From source file:org.jboss.aerogear.android.impl.authz.AuthzService.java
private void runAccountAction(OAuth2AuthzSession storedAccount, AuthzConfig config, final Map<String, String> data) throws OAuth2AuthorizationException { try {//from www . ja va2s .c om final URL accessTokenEndpoint = appendToBaseURL(config.getBaseURL(), config.getAccessTokenEndpoint()); final HttpProvider provider = getHttpProvider(accessTokenEndpoint); final String formTemplate = "%s=%s"; provider.setDefaultHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); final StringBuilder bodyBuilder = new StringBuilder(); String amp = ""; for (Map.Entry<String, String> entry : data.entrySet()) { bodyBuilder.append(amp); try { bodyBuilder.append(String.format(formTemplate, entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } amp = "&"; } HeaderAndBody headerAndBody; try { headerAndBody = provider.post(bodyBuilder.toString().getBytes("UTF-8")); } catch (HttpException exception) { if (exception.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST) { JsonElement response = new JsonParser().parse(new String(exception.getData())); JsonObject jsonResponseObject = response.getAsJsonObject(); String error = ""; if (jsonResponseObject.has("error")) { error = jsonResponseObject.get("error").getAsString(); } throw new OAuth2AuthorizationException(error); } else { throw exception; } } JsonElement response = new JsonParser().parse(new String(headerAndBody.getBody())); JsonObject jsonResponseObject = response.getAsJsonObject(); String accessToken = jsonResponseObject.get("access_token").getAsString(); storedAccount.setAccessToken(accessToken); //Will need to check this one day //String tokenType = jsonResponseObject.get("token_type").getAsString(); if (jsonResponseObject.has("expires_in")) { Long expiresIn = jsonResponseObject.get("expires_in").getAsLong(); Long expires_on = new Date().getTime() + expiresIn * 1000; storedAccount.setExpires_on(expires_on); } if (jsonResponseObject.has("refresh_token")) { String refreshToken = jsonResponseObject.get("refresh_token").getAsString(); if (!Strings.isNullOrEmpty(refreshToken)) { storedAccount.setRefreshToken(refreshToken); } } storedAccount.setAuthorizationCode(""); } catch (UnsupportedEncodingException ex) { //Should never happen... Log.d(AuthzService.class.getName(), null, ex); throw new RuntimeException(ex); } }
From source file:io.github.mike10004.vhs.testsupport.NanohttpdFormDataParser.java
/** * Decodes the Multipart Body data and put it into Key/Value pairs. */// ww w. ja v a2 s . c om @Override public List<FormDataPart> decodeMultipartFormData(MediaType contentType, byte[] data) throws BadMultipartFormDataException { Charset parentTypeEncoding = contentType.charset().or(DEFAULT_MULTIPART_FORM_DATA_ENCODING); String boundary = MultipartFormDataParser.getBoundaryOrDie(contentType); byte[] boundaryBytes = boundary.getBytes(BOUNDARY_ENCODING); ByteBuffer fbuf = ByteBuffer.wrap(data); int[] boundaryIdxs = getBoundaryPositions(fbuf, boundaryBytes); List<FormDataPart> parts = new ArrayList<>(boundaryIdxs.length); byte[] partHeaderBuff = new byte[MAX_HEADER_SIZE]; for (int boundaryIdx = 0; boundaryIdx < boundaryIdxs.length - 1; boundaryIdx++) { Multimap<String, String> headers = ArrayListMultimap.create(); fbuf.position(boundaryIdxs[boundaryIdx]); int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE; fbuf.get(partHeaderBuff, 0, len); MemoryBufferedReader in = new MemoryBufferedReader(partHeaderBuff, 0, len, parentTypeEncoding, len); int headerLines = 0; // First line is boundary string String mpline = in.readLine(); headerLines++; if (mpline == null || !mpline.contains(boundary)) { throw new MalformedMultipartFormDataException( "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary."); } // Parse the reset of the header lines mpline = in.readLine(); headerLines++; @Nullable String partContentType = null; @Nullable ContentDisposition disposition = null; while (mpline != null && mpline.trim().length() > 0) { Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline); if (matcher.matches()) { String attributeString = matcher.group(2); headers.put(HttpHeaders.CONTENT_DISPOSITION, attributeString); disposition = ContentDisposition.parse(attributeString); } matcher = CONTENT_TYPE_PATTERN.matcher(mpline); if (matcher.matches()) { partContentType = matcher.group(2).trim(); headers.put(HttpHeaders.CONTENT_TYPE, partContentType); } mpline = in.readLine(); headerLines++; } int partHeaderLength = 0; while (headerLines-- > 0) { partHeaderLength = skipOverNewLine(partHeaderBuff, partHeaderLength); } // Read the part data if (partHeaderLength >= len - 4) { throw new BadMultipartFormDataException("Multipart header size exceeds MAX_HEADER_SIZE."); } int partDataStart = boundaryIdxs[boundaryIdx] + partHeaderLength; int partDataEnd = boundaryIdxs[boundaryIdx + 1] - 4; fbuf.position(partDataStart); if (partContentType == null) { partContentType = DEFAULT_FORM_DATA_PART_CONTENT_TYPE.toString(); } // Read it into a file byte[] fileData = copyRegion(fbuf, partDataStart, partDataEnd - partDataStart); TypedContent file = TypedContent.identity(ByteSource.wrap(fileData), MediaType.parse(partContentType)); parts.add(new FormDataPart(headers, disposition, file)); } return parts; }
From source file:co.cask.cdap.messaging.client.ClientMessagingService.java
@Override public void rollback(TopicId topicId, RollbackDetail rollbackDetail) throws TopicNotFoundException, IOException { ByteBuffer requestBody = (rollbackDetail instanceof ClientRollbackDetail) ? ByteBuffer.wrap(((ClientRollbackDetail) rollbackDetail).getEncoded()) : encodeRollbackDetail(rollbackDetail); HttpRequest httpRequest = remoteClient .requestBuilder(HttpMethod.POST, createTopicPath(topicId) + "/rollback") .addHeader(HttpHeaders.CONTENT_TYPE, "avro/binary").withBody(requestBody).build(); HttpResponse response = remoteClient.execute(httpRequest); if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new TopicNotFoundException(topicId.getNamespace(), topicId.getTopic()); }/*from www .j ava2 s . c om*/ handleError(response, "Failed to rollback message in topic " + topicId + " with rollback detail " + rollbackDetail); }
From source file:org.jclouds.s3.filters.RequestAuthorizeSignatureV2.java
@VisibleForTesting void appendHttpHeaders(HttpRequest request, SortedSetMultimap<String, String> canonicalizedHeaders) { Multimap<String, String> headers = request.getHeaders(); for (Map.Entry<String, String> header : headers.entries()) { if (header.getKey() == null) { continue; }/* w w w . ja v a2s . c o m*/ String key = header.getKey().toString().toLowerCase(Locale.getDefault()); // Ignore any headers that are not particularly interesting. if (key.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE) || key.equalsIgnoreCase("Content-MD5") || key.equalsIgnoreCase(HttpHeaders.DATE) || key.startsWith("x-" + headerTag + "-")) { canonicalizedHeaders.put(key, header.getValue()); } } }
From source file:be.solidx.hot.web.AsyncStaticResourceServlet.java
protected void asyncLoadResource(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, final String contentType, final AsyncContext async) throws Exception { URL resourceUrl = getResourceURL(servletRequest, servletResponse); if (resourceUrl == null) { servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); async.complete();/*from w w w.j a v a 2 s . c om*/ return; } final URI uri = resourceUrl.toURI(); // Extract Servlet response of spring response wrapper if needed final ServletOutputStream outputStream; if (servletResponse instanceof SaveContextOnUpdateOrErrorResponseWrapper) { outputStream = ((SaveContextOnUpdateOrErrorResponseWrapper) servletResponse).getResponse() .getOutputStream(); } else { outputStream = servletResponse.getOutputStream(); } eventLoop.execute(new Runnable() { @Override public void run() { try { servletResponse.setHeader(com.google.common.net.HttpHeaders.CONTENT_TYPE, contentType); Path path = getPath(uri); // If file in ZIP, we load fully load it in memory and write it directly if (!commonConfig.jboss() && path.getFileSystem() instanceof ZipFileSystem) { byte[] bytes = Files.readAllBytes(path); servletResponse.setStatus(HttpStatus.OK.value()); writeBytesToResponseAsync(outputStream, bytes, async); } else { Promise<Void, Exception, Buffer> promise = fileLoader.loadResourceAsync(path) .fail(new FailCallback<Exception>() { @Override public void onFail(Exception result) { if (!servletResponse.isCommitted()) { servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); } try { outputStream.write(extractStackTrace(result).getBytes()); } catch (IOException e) { LOGGER.error("", e); } finally { async.complete(); } } }); writeBytesToResponseAsync(outputStream, promise, async); } } catch (Exception e) { LOGGER.error("Error", e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); writeBytesToResponseAsync(outputStream, extractStackTrace(e).getBytes(), async); } } }); }
From source file:com.tinspx.util.net.MultipartBody.java
private MultipartBody setContentType(@NonNull MediaType contentType, @Nullable String boundary, boolean init) { if (boundary != null) { contentType = contentType.withParameter(BOUNDARY, boundary); } else {/*w ww . ja va 2 s . com*/ List<String> b = contentType.parameters().get(BOUNDARY); if (b.isEmpty()) { boundary = init ? generateBoundary() : this.boundary; contentType = contentType.withParameter(BOUNDARY, boundary); } else if (b.size() > 1) { throw new IllegalArgumentException( String.format("type (%s) has multiple boundary parameters", contentType)); } else { boundary = b.get(0); } } checkBoundary(boundary); boundaryBytes = CharUtils.encodeAscii(boundary); this.boundary = boundary; headers.replaceValues(HttpHeaders.CONTENT_TYPE, Collections.singleton(contentType.toString())); type = contentType; valid = false; return this; }
From source file:co.cask.cdap.messaging.client.ClientMessagingService.java
/** * Makes a request to the server for writing to the messaging system * * @param request contains information about what to write * @param publish {@code true} to make publish call, {@code false} to make store call. * @return the response from the server//from w w w . j a v a2 s .c o m * @throws IOException if failed to perform the write operation * @throws TopicNotFoundException if the topic to write to does not exist */ private HttpResponse performWriteRequest(StoreRequest request, boolean publish) throws IOException, TopicNotFoundException { GenericRecord record = new GenericData.Record(Schemas.V1.PublishRequest.SCHEMA); if (request.isTransactional()) { record.put("transactionWritePointer", request.getTransactionWritePointer()); } record.put("messages", convertPayloads(request)); // Encode the request as avro ExposedByteArrayOutputStream os = new ExposedByteArrayOutputStream(); Encoder encoder = EncoderFactory.get().directBinaryEncoder(os, null); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(Schemas.V1.PublishRequest.SCHEMA); datumWriter.write(record, encoder); // Make the publish request String writeType = publish ? "publish" : "store"; TopicId topicId = request.getTopicId(); HttpRequest httpRequest = remoteClient .requestBuilder(HttpMethod.POST, createTopicPath(topicId) + "/" + writeType) .addHeader(HttpHeaders.CONTENT_TYPE, "avro/binary").withBody(os.toByteBuffer()).build(); HttpResponse response = remoteClient.execute(httpRequest); if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new TopicNotFoundException(topicId.getNamespace(), topicId.getTopic()); } handleError(response, "Failed to " + writeType + " message to topic " + topicId); return response; }
From source file:io.github.mike10004.vhs.testsupport.MakeFileUploadHar.java
private static MediaType getContentType(Map<String, String> headers) { return getHeaderValue(headers, HttpHeaders.CONTENT_TYPE, MediaType::parse, MediaType.OCTET_STREAM); }
From source file:org.smartdeveloperhub.harvesters.it.notification.NotificationConsumer.java
private void verifyHeader(final BasicProperties properties) throws IOException { final Object header = properties.getHeaders().get(HttpHeaders.CONTENT_TYPE); checkNotNull(header, "No %s header defined", HttpHeaders.CONTENT_TYPE); checkArgument(Notifications.MIME.equals(header.toString()), "Unsupported %s header (%s)", HttpHeaders.CONTENT_TYPE, header); }