List of usage examples for com.google.common.net HttpHeaders CONTENT_RANGE
String CONTENT_RANGE
To view the source code for com.google.common.net HttpHeaders CONTENT_RANGE.
Click Source Link
From source file:org.jclouds.glacier.binders.BindContentRangeToHeaders.java
@SuppressWarnings("unchecked") @Override/*from w w w.j a v a2 s .c o m*/ public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(input instanceof ContentRange, "This binder is only valid for Payload"); checkNotNull(request, "request"); ContentRange range = ContentRange.class.cast(input); return (R) request.toBuilder().addHeader(HttpHeaders.CONTENT_RANGE, range.buildHeader()).build(); }
From source file:org.jclouds.b2.functions.ParseB2ObjectFromResponse.java
@Override public B2Object apply(HttpResponse from) { Payload payload = from.getPayload(); MutableContentMetadata contentMeta = payload.getContentMetadata(); String fileId = from.getFirstHeaderOrNull(B2Headers.FILE_ID); String fileName;// w w w.j av a2s. c o m try { fileName = URLDecoder.decode(from.getFirstHeaderOrNull(B2Headers.FILE_NAME), "UTF-8"); } catch (UnsupportedEncodingException uee) { throw Throwables.propagate(uee); } String contentSha1 = from.getFirstHeaderOrNull(B2Headers.CONTENT_SHA1); ImmutableMap.Builder<String, String> fileInfo = ImmutableMap.builder(); for (Map.Entry<String, String> entry : from.getHeaders().entries()) { if (entry.getKey().regionMatches(true, 0, B2Headers.FILE_INFO_PREFIX, 0, B2Headers.FILE_INFO_PREFIX.length())) { String value; try { value = URLDecoder.decode(entry.getValue(), "UTF-8"); } catch (UnsupportedEncodingException uee) { throw Throwables.propagate(uee); } fileInfo.put(entry.getKey().substring(B2Headers.FILE_INFO_PREFIX.length()), value); } } Date uploadTimestamp = new Date(Long.parseLong(from.getFirstHeaderOrNull(B2Headers.UPLOAD_TIMESTAMP))); String contentRange = from.getFirstHeaderOrNull(HttpHeaders.CONTENT_RANGE); return B2Object.create(fileId, fileName, null, null, contentMeta.getContentLength(), contentSha1, contentMeta.getContentType(), fileInfo.build(), null, uploadTimestamp.getTime(), contentRange, payload); }
From source file:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java
/** * <p>//from w w w . j a va2 s . c o m * Write response with target relation and publishes events concerning the * download progress based on given update action status. * </p> * * <p> * The request supports RFC7233 range requests. * </p> * * @param artifact * the artifact * @param response * to be sent back to the requesting client * @param request * from the client * @param file * to be write to the client response * @param controllerManagement * to write progress updates to * @param statusId * of the {@link ActionStatus} * * @return http code * * @see <a href="https://tools.ietf.org/html/rfc7233">https://tools.ietf.org * /html/rfc7233</a> */ public static ResponseEntity<InputStream> writeFileResponse(final Artifact artifact, final HttpServletResponse response, final HttpServletRequest request, final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId) { ResponseEntity<InputStream> result; final String etag = artifact.getSha1Hash(); final Long lastModified = artifact.getLastModifiedAt() != null ? artifact.getLastModifiedAt() : artifact.getCreatedAt(); final long length = file.getSize(); response.reset(); response.setBufferSize(BUFFER_SIZE); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename()); response.setHeader(HttpHeaders.ETAG, etag); response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); final ByteRange full = new ByteRange(0, length - 1, length); final List<ByteRange> ranges = new ArrayList<>(); // Validate and process Range and If-Range headers. final String range = request.getHeader("Range"); if (range != null) { LOG.debug("range header for filename ({}) is: {}", artifact.getFilename(), range); // Range header matches"bytes=n-n,n-n,n-n..." if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length); LOG.debug("range header for filename ({}) is not satisfiable: ", artifact.getFilename()); return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); } // RFC: if the representation is unchanged, send me the part(s) that // I am requesting in // Range; otherwise, send me the entire representation. checkForShortcut(request, etag, lastModified, full, ranges); // it seems there are valid ranges result = extractRange(response, length, ranges, range); // return if range extraction turned out to be invalid if (result != null) { return result; } } // full request - no range if (ranges.isEmpty() || ranges.get(0).equals(full)) { LOG.debug("filename ({}) results into a full request: ", artifact.getFilename()); handleFullFileRequest(artifact, response, file, controllerManagement, statusId, full); result = new ResponseEntity<>(HttpStatus.OK); } // standard range request else if (ranges.size() == 1) { LOG.debug("filename ({}) results into a standard range request: ", artifact.getFilename()); handleStandardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT); } // multipart range request else { LOG.debug("filename ({}) results into a multipart range request: ", artifact.getFilename()); handleMultipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT); } return result; }
From source file:org.sonatype.nexus.repository.http.PartialFetchHandler.java
/** * Mutate the response into one that returns part of the payload. *//*from w w w.j a va 2s. c o m*/ private Response partialResponse(final Response response, final Payload payload, final Range<Long> requestedRange) { Response.Builder builder = new Response.Builder().copy(response) .status(Status.success(HttpStatus.PARTIAL_CONTENT)); Payload partialPayload = new PartialPayload(payload, requestedRange); builder.payload(partialPayload); // ResponseSender takes care of Content-Length header, via payload.size builder.header(HttpHeaders.CONTENT_RANGE, requestedRange.lowerEndpoint() + "-" + requestedRange.upperEndpoint() + "/" + payload.getSize()); return builder.build(); }
From source file:org.sonatype.nexus.repository.http.HttpResponses.java
public static Response rangeNotSatisfiable(final long contentSize) { return new Response.Builder().status(Status.failure(REQUESTED_RANGE_NOT_SATISFIABLE)) .header(HttpHeaders.CONTENT_LENGTH, "0").header(HttpHeaders.CONTENT_RANGE, "bytes */" + contentSize) .build();/*from w ww . j a v a 2s . c o m*/ }
From source file:org.sonatype.nexus.repository.partial.PartialFetchHandler.java
/** * Mutate the response into one that returns part of the payload. *//*from w ww .ja v a 2 s . co m*/ private PayloadResponse partialResponse(final PayloadResponse response, final Payload payload, final Range requestedRange) { response.setStatus(Status.success(HttpStatus.PARTIAL_CONTENT)); final Range<Long> rangeToSend = requestedRange; Payload partialPayload = new PartialPayload(payload, rangeToSend); response.setPayload(partialPayload); final Headers responseHeaders = response.getHeaders(); // ResponseSender takes care of Content-Length header, via payload.size responseHeaders.set(HttpHeaders.CONTENT_RANGE, rangeToSend.lowerEndpoint() + "-" + rangeToSend.upperEndpoint() + "/" + payload.getSize()); return response; }
From source file:org.apache.hadoop.hdfs.web.ByteRangeInputStream.java
private static long getStreamLength(HttpURLConnection connection, Map<String, List<String>> headers) throws IOException { String cl = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH); if (cl == null) { // Try to get the content length by parsing the content range // because HftpFileSystem does not return the content length // if the content is partial. if (connection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) { cl = connection.getHeaderField(HttpHeaders.CONTENT_RANGE); return getLengthFromRange(cl); } else {/*from w ww . ja v a 2 s . c om*/ throw new IOException(HttpHeaders.CONTENT_LENGTH + " is missing: " + headers); } } return Long.parseLong(cl); }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.reader.GetRecordsMessageBodyReader.java
@Override public CswRecordCollection readFrom(Class<CswRecordCollection> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream inStream) throws IOException, WebApplicationException { CswRecordCollection cswRecords = null; Map<String, Serializable> resourceProperties = new HashMap<>(); // Check if the server returned a Partial Content response (hopefully in response to a range // header)/*from w w w . j a v a2s.c om*/ String contentRangeHeader = httpHeaders.getFirst(HttpHeaders.CONTENT_RANGE); if (StringUtils.isNotBlank(contentRangeHeader)) { contentRangeHeader = StringUtils.substringBetween(contentRangeHeader.toLowerCase(), "bytes ", "-"); long bytesSkipped = Long.parseLong(contentRangeHeader); resourceProperties.put(BYTES_SKIPPED, Long.valueOf(bytesSkipped)); } // If the following HTTP header exists and its value is true, the input stream will contain // raw product data String productRetrievalHeader = httpHeaders.getFirst(CswConstants.PRODUCT_RETRIEVAL_HTTP_HEADER); if (productRetrievalHeader != null && productRetrievalHeader.equalsIgnoreCase("TRUE")) { String fileName = handleContentDispositionHeader(httpHeaders); cswRecords = new CswRecordCollection(); cswRecords.setResource(new ResourceImpl(inStream, mediaType.toString(), fileName)); cswRecords.setResourceProperties(resourceProperties); return cswRecords; } // Save original input stream for any exception message that might need to be // created String originalInputStream = IOUtils.toString(inStream, "UTF-8"); LOGGER.debug("Converting to CswRecordCollection: \n {}", originalInputStream); // Re-create the input stream (since it has already been read for potential // exception message creation) inStream = new ByteArrayInputStream(originalInputStream.getBytes("UTF-8")); try { HierarchicalStreamReader reader = new XppReader(new InputStreamReader(inStream, StandardCharsets.UTF_8), XmlPullParserFactory.newInstance().newPullParser()); cswRecords = (CswRecordCollection) xstream.unmarshal(reader, null, argumentHolder); } catch (XmlPullParserException e) { LOGGER.debug("Unable to create XmlPullParser, and cannot parse CSW Response.", e); } catch (XStreamException e) { // If an ExceptionReport is sent from the remote CSW site it will be sent with an // JAX-RS "OK" status, hence the ErrorResponse exception mapper will not fire. // Instead the ExceptionReport will come here and be treated like a GetRecords // response, resulting in an XStreamException since ExceptionReport cannot be // unmarshalled. So this catch clause is responsible for catching that XStream // exception and creating a JAX-RS response containing the original stream // (with the ExceptionReport) and rethrowing it as a WebApplicatioNException, // which CXF will wrap as a ClientException that the CswSource catches, converts // to a CswException, and logs. ByteArrayInputStream bis = new ByteArrayInputStream( originalInputStream.getBytes(StandardCharsets.UTF_8)); ResponseBuilder responseBuilder = Response.ok(bis); responseBuilder.type("text/xml"); Response response = responseBuilder.build(); throw new WebApplicationException(e, response); } finally { IOUtils.closeQuietly(inStream); } return cswRecords; }
From source file:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java
private static void handleFullFileRequest(final Artifact artifact, final HttpServletResponse response, final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, final ByteRange full) { final ByteRange r = full; response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength())); try (InputStream inputStream = file.getFileInputStream()) { copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(), r.getLength());/*ww w. ja v a2 s .co m*/ } catch (final IOException e) { LOG.error("fullfileRequest of file ({}) failed!", artifact.getFilename(), e); throw new FileSteamingFailedException(artifact.getFilename()); } }
From source file:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java
private static ResponseEntity<InputStream> extractRange(final HttpServletResponse response, final long length, final List<ByteRange> ranges, final String range) { if (ranges.isEmpty()) { for (final String part : range.substring(6).split(",")) { long start = sublong(part, 0, part.indexOf('-')); long end = sublong(part, part.indexOf('-') + 1, part.length()); if (start == -1) { start = length - end;//w w w.j av a 2 s . c o m end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return // 416. if (start > end) { response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length); return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); } // Add range. ranges.add(new ByteRange(start, end, length)); } } return null; }