Example usage for com.google.common.net HttpHeaders CONTENT_DISPOSITION

List of usage examples for com.google.common.net HttpHeaders CONTENT_DISPOSITION

Introduction

In this page you can find the example usage for com.google.common.net HttpHeaders CONTENT_DISPOSITION.

Prototype

String CONTENT_DISPOSITION

To view the source code for com.google.common.net HttpHeaders CONTENT_DISPOSITION.

Click Source Link

Document

The HTTP Content-Disposition header field name.

Usage

From source file:gmusic.api.api.comm.FormBuilder.java

private final void addField(final String key, final String value) throws IOException {
    final StringBuilder sb = new StringBuilder();

    sb.append(String.format("\r\n--%1$s\r\n", boundary));
    sb.append(HttpHeaders.CONTENT_DISPOSITION + ": form-data;");
    sb.append(String.format("name=\"%1$s\";\r\n\r\n%2$s", key, value));

    outputStream.write(sb.toString().getBytes());
}

From source file:gmusic.api.api.comm.FormBuilder.java

public final void addFile(final String name, final String fileName, final byte[] file) throws IOException {
    final StringBuilder sb = new StringBuilder();

    sb.append(String.format("\r\n--%1$s\r\n", boundary));
    sb.append(/*w  ww  .  ja  va 2  s.c  o m*/
            String.format(HttpHeaders.CONTENT_DISPOSITION + ": form-data; name=\"%1$s\"; filename=\"%2$s\"\r\n",
                    name, fileName));

    sb.append(String.format(HttpHeaders.CONTENT_TYPE + ": %1$s\r\n\r\n", ContentType.APPLICATION_OCTET_STREAM));

    outputStream.write(sb.toString().getBytes());
    outputStream.write(file, 0, file.length);
}

From source file:org.ambraproject.rhino.rest.controller.IngestibleController.java

@Transactional(rollbackFor = { Throwable.class })
@RequestMapping(value = "/articles/{doi}/ingestions/{number}/ingestible", method = RequestMethod.GET)
public void repack(HttpServletResponse response, @PathVariable("doi") String doi,
        @PathVariable("number") int ingestionNumber) throws IOException {
    ArticleIngestionIdentifier ingestionId = ArticleIngestionIdentifier.create(DoiEscaping.unescape(doi),
            ingestionNumber);//  w  w  w .ja v  a2s  .  com

    Archive archive = articleCrudService.repack(ingestionId);
    response.setStatus(HttpStatus.OK.value());
    response.setContentType("application/zip");
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + archive.getArchiveName());
    try (OutputStream outputStream = response.getOutputStream()) {
        archive.write(outputStream);
    }
}

From source file:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java

/**
 * <p>// w w  w  . j  a  v  a  2  s .  c  om
 * 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.ambraproject.rhino.rest.controller.AssetFileCrudController.java

private void serve(HttpServletRequest request, HttpServletResponse response, RepoObjectMetadata objMeta)
        throws IOException {
    objMeta.getContentType().ifPresent((String contentType) -> {
        response.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
    });/*from   w  ww. j  a v a 2s .  co m*/

    objMeta.getDownloadName().ifPresent((String downloadName) -> {
        String contentDisposition = "attachment; filename=" + downloadName;
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
    });

    Timestamp timestamp = objMeta.getTimestamp();
    setLastModifiedHeader(response, timestamp);
    if (!checkIfModifiedSince(request, timestamp)) {
        response.setStatus(HttpStatus.NOT_MODIFIED.value());
        return;
    }

    List<URL> reproxyUrls = objMeta.getReproxyUrls();
    if (clientSupportsReproxy(request) && reproxyUrls != null && !reproxyUrls.isEmpty()) {
        String reproxyUrlHeader = REPROXY_URL_JOINER.join(reproxyUrls);

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("X-Reproxy-URL", reproxyUrlHeader);
        response.setHeader("X-Reproxy-Cache-For", REPROXY_CACHE_FOR_HEADER);
    } else {
        try (InputStream fileStream = contentRepoService.getRepoObject(objMeta.getVersion());
                OutputStream responseStream = response.getOutputStream()) {
            ByteStreams.copy(fileStream, responseStream);
        }
    }
}

From source file:org.agileframework.web.servlet.Servlets.java

/**
 * ??Header./*from   w  w  w  . j a  v a  2s.  c  o m*/
 * 
 * @param fileName ???.
 */
public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
    try {
        //???
        String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
    } catch (UnsupportedEncodingException e) {
    }
}

From source file:com.agileEAP.web.Servlets.java

/**
 * ??Header.//from w  w  w .  j av  a 2s  . c om
 * 
 * @param fileName ???.
 */
public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
    try {
        // ???
        String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
    } catch (UnsupportedEncodingException e) {
    }
}

From source file:com.cnksi.core.web.utils.Servlets.java

/**
 * ??Header./*from   ww  w .j  av  a  2  s  . c o  m*/
 * 
 * @param fileName ???.
 */
public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {

    try {
        // ???
        String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
    } catch (UnsupportedEncodingException e) {
    }
}

From source file:com.sobey.framework.utils.Servlets.java

/**
 * ??Header.//from w  w w.ja  v  a  2  s. c  o  m
 * 
 * @param fileName
 *            ???.
 */
public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
    try {

        // ???

        String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");

        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");

    } catch (UnsupportedEncodingException e) {
    }
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtDownloadResource.java

/**
 * Handles the GET request for downloading an artifact.
 * /*from  w w w .  jav a 2  s  . c om*/
 * @param downloadId
 *            the generated download id
 * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if
 *         successful
 */
@Override
@ResponseBody
public ResponseEntity<Void> downloadArtifactByDownloadId(@PathVariable("downloadId") final String downloadId) {
    try {
        final DownloadArtifactCache artifactCache = downloadIdCache.get(downloadId);
        if (artifactCache == null) {
            LOGGER.warn("Download Id {} could not be found", downloadId);
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        DbArtifact artifact = null;

        if (DownloadType.BY_SHA1.equals(artifactCache.getDownloadType())) {
            artifact = artifactRepository.getArtifactBySha1(artifactCache.getId());
        } else {
            LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType());
        }

        if (artifact == null) {
            LOGGER.warn("Artifact with cached id {} and download type {} could not be found.",
                    artifactCache.getId(), artifactCache.getDownloadType());
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        final HttpServletResponse response = requestResponseContextHolder.getHttpServletResponse();
        final String etag = artifact.getHashes().getSha1();
        final long length = artifact.getSize();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + downloadId);
        response.setHeader(HttpHeaders.ETAG, etag);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setContentLengthLong(length);

        try (InputStream inputstream = artifact.getFileInputStream()) {
            ByteStreams.copy(inputstream,
                    requestResponseContextHolder.getHttpServletResponse().getOutputStream());
        } catch (final IOException e) {
            LOGGER.error("Cannot copy streams", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    } finally {
        downloadIdCache.evict(downloadId);
    }

    return ResponseEntity.ok().build();
}