• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java ContentDisposition类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中org.glassfish.jersey.media.multipart.ContentDisposition的典型用法代码示例。如果您正苦于以下问题:Java ContentDisposition类的具体用法?Java ContentDisposition怎么用?Java ContentDisposition使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ContentDisposition类属于org.glassfish.jersey.media.multipart包,在下文中一共展示了ContentDisposition类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: createObject

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
/**
 * Creates a new object.
 *
 * This originally used application/octet-stream;qs=1001 as a workaround
 * for JERSEY-2636, to ensure requests without a Content-Type get routed here.
 * This qs value does not parse with newer versions of Jersey, as qs values
 * must be between 0 and 1.  We use qs=1.000 to mark where this historical
 * anomaly had been.
 *
 * @param contentDisposition the content Disposition value
 * @param requestContentType the request content type
 * @param slug the slug value
 * @param requestBodyStream  the request body stream
 * @param link the link value
 * @param digest the digest header
 * @return 201
 * @throws InvalidChecksumException if invalid checksum exception occurred
 * @throws IOException if IO exception occurred
 * @throws MalformedRdfException if malformed rdf exception occurred
 */
@POST
@Consumes({MediaType.APPLICATION_OCTET_STREAM + ";qs=1.000", WILDCARD})
@Produces({TURTLE_WITH_CHARSET + ";qs=1.0", JSON_LD + ";qs=0.8",
        N3_WITH_CHARSET, N3_ALT2_WITH_CHARSET, RDF_XML, NTRIPLES, TEXT_PLAIN_WITH_CHARSET,
        TURTLE_X, TEXT_HTML_WITH_CHARSET, "*/*"})
public Response createObject(@HeaderParam(CONTENT_DISPOSITION) final ContentDisposition contentDisposition,
                             @HeaderParam(CONTENT_TYPE) final MediaType requestContentType,
                             @HeaderParam("Slug") final String slug,
                             @ContentLocation final InputStream requestBodyStream,
                             @HeaderParam(LINK) final String link,
                             @HeaderParam("Digest") final String digest)
        throws InvalidChecksumException, IOException, MalformedRdfException {
    LOGGER.info("POST: {}", externalPath);

    final ContainerService containerService = getContainerService();
    final URI resourceUri = createFromPath(externalPath);

    //check that resource exists
    if (!containerService.exists(resourceUri)) {
        if (!isRoot(resourceUri)) {
            return status(NOT_FOUND).build();
        } else {
            createRoot();
        }
    }

    final String newResourceName = slug == null ? UUID.randomUUID().toString() : slug;
    final String resourcePath = (isRoot(resourceUri) ? "" : resourceUri.getPath());
    final URI newResourceUri = createFromPath(resourcePath + "/" + newResourceName);
    final Container container = containerService.findOrCreate(newResourceUri);
    final Model model = ModelFactory.createDefaultModel();

    model.read(requestBodyStream, container.getIdentifier().toString(), "TTL");
    final Stream<Triple> triples = model.listStatements().toList().stream().map(Statement::asTriple);
    container.updateTriples(triples);
    return created(toExternalURI(container.getIdentifier(), headers)).build();
}
 
开发者ID:duraspace,项目名称:lambdora,代码行数:58,代码来源:LambdoraLdp.java


示例2: replaceResourceBinaryWithStream

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
protected void replaceResourceBinaryWithStream(final FedoraBinary result,
                                               final InputStream requestBodyStream,
                                               final ContentDisposition contentDisposition,
                                               final MediaType contentType,
                                               final Collection<String> checksums) throws InvalidChecksumException {
    final Collection<URI> checksumURIs = checksums == null ?
            new HashSet<>() : checksums.stream().map(checksum -> checksumURI(checksum)).collect(Collectors.toSet());
    final String originalFileName = contentDisposition != null ? contentDisposition.getFileName() : "";
    final String originalContentType = contentType != null ? contentType.toString() : "";

    result.setContent(requestBodyStream,
            originalContentType,
            checksumURIs,
            originalFileName,
            storagePolicyDecisionPoint);
}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:17,代码来源:ContentExposingResource.java


示例3: testHeadDatastream

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
@Test
public void testHeadDatastream() throws IOException, ParseException {
    final String id = getRandomUniqueId();
    createDatastream(id, "x", "123");

    final HttpHead headObjMethod = headObjMethod(id + "/x");
    try (final CloseableHttpResponse response = execute(headObjMethod)) {
        assertEquals(OK.getStatusCode(), response.getStatusLine().getStatusCode());
        assertEquals(TEXT_PLAIN, response.getFirstHeader(CONTENT_TYPE).getValue());
        assertEquals("3", response.getFirstHeader(CONTENT_LENGTH).getValue());
        assertEquals("bytes", response.getFirstHeader("Accept-Ranges").getValue());
        final ContentDisposition disposition =
                new ContentDisposition(response.getFirstHeader(CONTENT_DISPOSITION).getValue());
        assertEquals("attachment", disposition.getType());
    }
}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:17,代码来源:FedoraLdpIT.java


示例4: testHeadExternalDatastream

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
@Test
public void testHeadExternalDatastream() throws IOException, ParseException {
    final String externalContentType = "message/external-body;access-type=URL;url=\"some:uri\"";

    final String id = getRandomUniqueId();
    final HttpPut put = putObjMethod(id);
    put.addHeader(CONTENT_TYPE, externalContentType);
    put.addHeader(LINK, NON_RDF_SOURCE_LINK_HEADER);
    assertEquals(CREATED.getStatusCode(), getStatus(put));

    // Configure HEAD request to NOT follow redirects
    final HttpHead headObjMethod = headObjMethod(id);
    final RequestConfig.Builder requestConfig = RequestConfig.custom();
    requestConfig.setRedirectsEnabled(false);
    headObjMethod.setConfig(requestConfig.build());

    try (final CloseableHttpResponse response = execute(headObjMethod)) {
        assertEquals(TEMPORARY_REDIRECT.getStatusCode(), response.getStatusLine().getStatusCode());
        assertEquals(externalContentType, response.getFirstHeader(CONTENT_TYPE).getValue());
        assertEquals("some:uri", response.getFirstHeader(CONTENT_LOCATION).getValue());
        assertEquals("bytes", response.getFirstHeader("Accept-Ranges").getValue());
        final ContentDisposition disposition =
                new ContentDisposition(response.getFirstHeader(CONTENT_DISPOSITION).getValue());
        assertEquals("attachment", disposition.getType());
    }
}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:27,代码来源:FedoraLdpIT.java


示例5: testGetExternalDatastream

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
@Test
public void testGetExternalDatastream() throws IOException, ParseException {
    final String externalContentType = "message/external-body;access-type=URL;url=\"some:uri\"";

    final String id = getRandomUniqueId();
    final HttpPut put = putObjMethod(id);
    put.addHeader(CONTENT_TYPE, externalContentType);
    assertEquals(CREATED.getStatusCode(), getStatus(put));

    // Configure HEAD request to NOT follow redirects
    final HttpGet getObjMethod = getObjMethod(id);
    final RequestConfig.Builder requestConfig = RequestConfig.custom();
    requestConfig.setRedirectsEnabled(false);
    getObjMethod.setConfig(requestConfig.build());

    try (final CloseableHttpResponse response = execute(getObjMethod)) {
        assertEquals(TEMPORARY_REDIRECT.getStatusCode(), response.getStatusLine().getStatusCode());
        assertEquals(externalContentType, response.getFirstHeader(CONTENT_TYPE).getValue());
        assertEquals("some:uri", response.getFirstHeader(CONTENT_LOCATION).getValue());
        assertEquals("bytes", response.getFirstHeader("Accept-Ranges").getValue());
        final ContentDisposition disposition =
                new ContentDisposition(response.getFirstHeader(CONTENT_DISPOSITION).getValue());
        assertEquals("attachment", disposition.getType());
    }
}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:26,代码来源:FedoraLdpIT.java


示例6: testGetDatastream

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
@Test
public void testGetDatastream() throws IOException, ParseException {
    final String id = getRandomUniqueId();
    createObjectAndClose(id);
    createDatastream(id, "ds1", "foo");

    try (final CloseableHttpResponse response = execute(getDSMethod(id, "ds1"))) {
        assertEquals("Wasn't able to retrieve a datastream!", OK.getStatusCode(), getStatus(response));
        assertEquals(TEXT_PLAIN, response.getFirstHeader(CONTENT_TYPE).getValue());
        assertEquals("3", response.getFirstHeader(CONTENT_LENGTH).getValue());
        assertEquals("bytes", response.getFirstHeader("Accept-Ranges").getValue());
        final ContentDisposition disposition =
                new ContentDisposition(response.getFirstHeader(CONTENT_DISPOSITION).getValue());
        assertEquals("attachment", disposition.getType());

        final Collection<String> links = getLinkHeaders(response);
        final String describedByHeader =
                "<" + serverAddress + id + "/ds1/" + FCR_METADATA + ">; rel=\"describedby\"";
        assertTrue("Didn't find 'describedby' link header!", links.contains(describedByHeader));
    }
}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:22,代码来源:FedoraLdpIT.java


示例7: createOrReplaceObjectRdf

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
/**
 * Create a resource at a specified path, or replace triples with provided RDF.
 *
 * @param requestContentType the request content type
 * @param requestBodyStream  the request body stream
 * @param contentDisposition the content disposition value
 * @param ifMatch            the if-match value
 * @param links              the link values
 * @param digest             the digest header
 * @return 204
 * @throws InvalidChecksumException      if invalid checksum exception occurred
 * @throws MalformedRdfException         if malformed rdf exception occurred
 * @throws UnsupportedAlgorithmException
 */
@PUT
@Consumes
public Response createOrReplaceObjectRdf(
    @HeaderParam(CONTENT_TYPE) final MediaType requestContentType,
    @ContentLocation final InputStream requestBodyStream,
    @HeaderParam(CONTENT_DISPOSITION) final ContentDisposition contentDisposition,
    @HeaderParam("If-Match") final String ifMatch,
    @HeaderParam(LINK) final List<String> links,
    @HeaderParam("Digest") final String digest)
    throws InvalidChecksumException, MalformedRdfException, UnsupportedAlgorithmException {

    final URI internalUri = createFromPath(externalPath);
    if (isRoot(internalUri)) {
        //method not allowed if root
        return Response.status(METHOD_NOT_ALLOWED).build();
    }

    final ContainerService containerService = getContainerService();
    //create resource if exists
    if (!containerService.exists(internalUri)) {
        final Container container = containerService.findOrCreate(internalUri);
        final Model model = ModelFactory.createDefaultModel();
        model.read(requestBodyStream, null, "TTL");
        final Stream<Triple> triples = model.listStatements().toList().stream().map(Statement::asTriple);
        container.updateTriples(triples);
        return created(toExternalURI(container.getIdentifier(), headers)).build();
    } else {
        //TODO delete resource, create resource, and update triples.
        return noContent().build();
    }
}
 
开发者ID:duraspace,项目名称:lambdora,代码行数:46,代码来源:LambdoraLdp.java


示例8: verifyOutput

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
@Test
public void verifyOutput()
    throws IOException, SAXException, ParserConfigurationException, ParseException {
  Configuration configuration = mock(Configuration.class);
  DatasetConfig datasetConfig = new DatasetConfig();
  datasetConfig.setFullPathList(path.toPathList());
  TableauMessageBodyGenerator generator = new TableauMessageBodyGenerator(configuration, NodeEndpoint.newBuilder().setAddress("foo").setUserPort(12345).build());
  MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  assertTrue(generator.isWriteable(datasetConfig.getClass(), null, null, WebServer.MediaType.APPLICATION_TDS_TYPE));
  generator.writeTo(datasetConfig, DatasetConfig.class, null, new Annotation[] {}, WebServer.MediaType.APPLICATION_TDS_TYPE, httpHeaders, baos);

  // Convert the baos into a DOM Tree to verify content
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  Document document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));

  NodeList connections = document.getDocumentElement().getElementsByTagName("connection");

  assertEquals(1, connections.getLength());
  Element connection = (Element) connections.item(0);
  assertEquals("genericodbc", connection.getAttribute("class"));
  assertEquals("Dremio Connector", connection.getAttribute("odbc-driver"));
  assertEquals("DREMIO", connection.getAttribute("dbname"));
  assertEquals(path.toParentPath(), connection.getAttribute("schema"));

  NodeList relations = connection.getElementsByTagName("relation");
  assertEquals(1, relations.getLength());
  Element relation = (Element) relations.item(0);
  assertEquals("table", relation.getAttribute("type"));
  assertEquals(tableName, relation.getAttribute("table"));

  // Also check that Content-Disposition header is set with a filename ending by tds
  ContentDisposition contentDisposition = new ContentDisposition((String) httpHeaders.getFirst(HttpHeaders.CONTENT_DISPOSITION));
  assertTrue("filename should end with .tds", contentDisposition.getFileName().endsWith(".tds"));
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:36,代码来源:TestTableauMessageBodyGenerator.java


示例9: getApplicationInputFile

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
/**
   * Convert the provided profile data to an input file using
   * the transform stored in the template metadata. 
   * @param pFileId the ID of the file to convert, as obtained from the
   *               response to the convert call.
   * @return the application input file specified by the fileId
   */
  @GET
  @Path("inputFile/{fileId}")
  public Response getApplicationInputFile(
      @PathParam("fileId") String pFileId,
      @Context HttpServletRequest pRequest) {
  	
  	sLog.debug("Request to get application input file with ID: " + pFileId);
  	
  	String fileDirPath = _context.getRealPath("temp");
  	final File dataFile = new File(fileDirPath + File.separator + "output_xml_" + pFileId + ".xml");
  	if(!dataFile.exists()) {
  		return Response.status(Status.NOT_FOUND).entity("Request app input data file could not be found.").build();
  	}
  	
  	StreamingOutput so = new StreamingOutput() {
	@Override
	public void write(OutputStream pOut) throws IOException,
			WebApplicationException {

		FileInputStream in = new FileInputStream(dataFile);
		byte[] data = new byte[1024];
		int dataRead = -1;
		while((dataRead = in.read(data)) != -1) {
			pOut.write(data, 0, dataRead);
		}
		pOut.close();
		in.close();
	}
};

// Create the content disposition object for the file download
ContentDisposition cd = ContentDisposition.type("attachment").creationDate(new Date()).fileName("tempss_input_file_" + pFileId + ".xml").build();

NewCookie c = new NewCookie("fileDownload","true", "/",null, null, NewCookie.DEFAULT_MAX_AGE, false);
return Response.status(Status.OK).
		header("Content-Disposition", cd).
		header("Content-Type", "application/xml").
		cookie(c).entity(so).build();
  }
 
开发者ID:london-escience,项目名称:tempss,代码行数:47,代码来源:ProfileRestResource.java


示例10: verifyContentDispositionFilename

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
private void verifyContentDispositionFilename(final String location, final String filename)
        throws IOException, ParseException {
    final HttpHead head = new HttpHead(location);
    try (final CloseableHttpResponse headResponse = execute(head)) {
        final Header header = headResponse.getFirstHeader(CONTENT_DISPOSITION);
        assertNotNull(header);

        final ContentDisposition contentDisposition = new ContentDisposition(header.getValue());
        assertEquals(filename, contentDisposition.getFileName());
    }
}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:12,代码来源:FedoraLdpIT.java


示例11: verifyNativeOutput

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
@Test
public void verifyNativeOutput()
    throws IOException, SAXException, ParserConfigurationException, ParseException {
  Configuration configuration = mock(Configuration.class);
  DatasetConfig datasetConfig = new DatasetConfig();
  datasetConfig.setFullPathList(path.toPathList());

  // create a schema to test the metadata output for native connectors
  datasetConfig.setType(DatasetType.PHYSICAL_DATASET);
  BatchSchema schema = BatchSchema.newBuilder()
    .addField(new Field("string", FieldType.nullable(ArrowType.Utf8.INSTANCE), null))
    .addField(new Field("bool", FieldType.nullable(ArrowType.Bool.INSTANCE), null))
    .addField(new Field("decimal", FieldType.nullable(new ArrowType.Decimal(0, 0)), null))
    .addField(new Field("int", FieldType.nullable(new ArrowType.Int(8, false)), null))
    .addField(new Field("date", FieldType.nullable(new ArrowType.Date(DateUnit.MILLISECOND)), null))
    .addField(new Field("time", FieldType.nullable(new ArrowType.Time(TimeUnit.MILLISECOND, 8)), null))
    .build();
  datasetConfig.setRecordSchema(schema.toByteString());

  TableauMessageBodyGenerator generator = new TableauMessageBodyGenerator(configuration, NodeEndpoint.newBuilder().setAddress("foo").setUserPort(12345).build());
  MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  assertTrue(generator.isWriteable(datasetConfig.getClass(), null, null, WebServer.MediaType.APPLICATION_TDS_DRILL_TYPE));
  generator.writeTo(datasetConfig, DatasetConfig.class, null, new Annotation[] {}, WebServer.MediaType.APPLICATION_TDS_DRILL_TYPE, httpHeaders, baos);

  // Convert the baos into a DOM Tree to verify content
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  Document document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));

  NodeList connections = document.getDocumentElement().getElementsByTagName("connection");

  assertEquals(1, connections.getLength());
  Element connection = (Element) connections.item(0);

  assertEquals("drill", connection.getAttribute("class"));
  assertEquals("Direct", connection.getAttribute("connection-type"));
  assertEquals("foo", connection.getAttribute("server"));
  assertEquals("12345", connection.getAttribute("port"));
  assertEquals(path.toParentPath(), connection.getAttribute("schema"));

  NodeList relations = connection.getElementsByTagName("relation");
  assertEquals(1, relations.getLength());
  Element relation = (Element) relations.item(0);
  assertEquals("table", relation.getAttribute("type"));
  assertEquals(tableName, relation.getAttribute("table"));

  // metadata tests
  NodeList metadataRecords = document.getDocumentElement().getElementsByTagName("metadata-record");

  assertEquals(metadataRecords.getLength(), schema.getFieldCount());
  assertEqualsMetadataRecord(metadataRecords.item(0), "[string]", "string");
  assertEqualsMetadataRecord(metadataRecords.item(1), "[bool]", "boolean");
  assertEqualsMetadataRecord(metadataRecords.item(2), "[decimal]", "real");
  assertEqualsMetadataRecord(metadataRecords.item(3), "[int]", "integer");
  assertEqualsMetadataRecord(metadataRecords.item(4), "[date]", "date");
  assertEqualsMetadataRecord(metadataRecords.item(5), "[time]", "datetime");

  // Also check that Content-Disposition header is set with a filename ending by tds
  ContentDisposition contentDisposition = new ContentDisposition((String) httpHeaders.getFirst(HttpHeaders.CONTENT_DISPOSITION));
  assertTrue("filename should end with .tds", contentDisposition.getFileName().endsWith(".tds"));
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:62,代码来源:TestTableauMessageBodyGenerator.java


示例12: addInlineContentDispositionHeader

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
void addInlineContentDispositionHeader(String fileName) {
    ContentDisposition contentDisposition = ContentDisposition.type("inline").fileName(fileName).build();
    httpServletResponse.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
}
 
开发者ID:openregister,项目名称:openregister-java,代码行数:5,代码来源:HttpServletResponseAdapter.java


示例13: exist

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
/**
 * Retrieves a file. Technically, this operation returns the representation of a file <i>HTTP
 * resource</i> whose URI is fully determined by the <tt>id</tt> query parameter that encodes
 * the URI of the KnowledgeStore resource the file refers to. The operation:
 * <ul>
 * <li>supports the use of HTTP preconditions in the form of If-Match, If-None-Match,
 * If-Modified-Since, If-Unmodified-Since headers;</li>
 * <li>allows the client to accept only representations in a certain MIME type, via Accept
 * header;</li>
 * <li>can enable / disable the use of server-side caches via header Cache-Control (specify
 * <tt>no-cache</tt> or <tt>no-store</tt> to disable caches).</li>
 * </ul>
 *
 * @param id
 *            the URI identifier of the KnowledgeStore resource (mandatory)
 * @param accept
 *            the MIME type accepted by the client (optional); a 406 NOT ACCEPTABLE response
 *            will be returned if the file representation has a non-compatible MIME type
 * @return the file content, on success, encoded using the specific file MIME type
 * @throws Exception
 *             on error
 */
@GET
@Produces("*/*")
@TypeHint(InputStream.class)
@StatusCodes({
        @ResponseCode(code = 200, condition = "if the file is found and its representation "
                + "is returned"),
        @ResponseCode(code = 404, condition = "if the requested file does not exist (the "
                + "associated resource may exist or not)") })
@ResponseHeaders({
        @ResponseHeader(name = "Content-Language", description = "the 2-letters ISO 639 "
                + "language code for file representation, if known"),
        @ResponseHeader(name = "Content-Disposition", description = "a content disposition "
                + "directive for browsers, including the suggested file name and date for "
                + "saving the file"),
        @ResponseHeader(name = "Content-MD5", description = "the MD5 hash of the file "
                + "representation") })
public Response get(@QueryParam(Protocol.PARAMETER_ID) final URI id,
        @HeaderParam(HttpHeaders.ACCEPT) @DefaultValue(MediaType.WILDCARD) final String accept)
        throws Exception {

    // Check query string parameters
    checkNotNull(id, Outcome.Status.ERROR_INVALID_INPUT, "Missing 'id' query parameter");

    // Retrieve the file to return
    final Representation representation = getSession() //
            .download(id) //
            .timeout(getTimeout()) //
            .accept(accept.split(",")) //
            .caching(isCachingEnabled()) //
            .exec();

    // Fail if file does not exist
    checkNotNull(representation, Outcome.Status.ERROR_OBJECT_NOT_FOUND,
            "Specified file does not exist");
    closeOnCompletion(representation);

    // Retrieve file metadata and build the resulting Content-Disposition header
    final Record metadata = representation.getMetadata();
    final Long fileSize = metadata.getUnique(NFO.FILE_SIZE, Long.class, null);
    final String fileName = metadata.getUnique(NFO.FILE_NAME, String.class, null);
    final String mimeType = metadata.getUnique(NIE.MIME_TYPE, String.class, null);
    final Date lastModified = extractLastModified(representation);
    final String tag = extractMD5(representation);
    final ContentDisposition disposition = ContentDisposition.type("attachment")
            .fileName(fileName) //
            .modificationDate(lastModified) //
            .size(fileSize != null ? fileSize : -1) //
            .build();

    // Validate client preconditions, do negotiation and handle probe requests
    init(false, mimeType, lastModified, tag);

    // Stream the file to the client. Note that Content-Length is not set as it will not be
    // valid after GZIP compression is applied (Jersey should remove it, but it doesn't)
    return newResponseBuilder(Status.OK, representation, null).header(
            HttpHeaders.CONTENT_DISPOSITION, disposition).build();
}
 
开发者ID:dkmfbk,项目名称:knowledgestore,代码行数:80,代码来源:Files.java


示例14: addResourceHttpHeaders

import org.glassfish.jersey.media.multipart.ContentDisposition; //导入依赖的package包/类
/**
 * Add any resource-specific headers to the response
 * @param resource the resource
 */
protected void addResourceHttpHeaders(final FedoraResource resource) {
    if (resource instanceof FedoraBinary) {
        final FedoraBinary binary = (FedoraBinary)resource;
        final Date createdDate = binary.getCreatedDate() != null ? Date.from(binary.getCreatedDate()) : null;
        final Date modDate = binary.getLastModifiedDate() != null ? Date.from(binary.getLastModifiedDate()) : null;

        final ContentDisposition contentDisposition = ContentDisposition.type("attachment")
                .fileName(binary.getFilename())
                .creationDate(createdDate)
                .modificationDate(modDate)
                .size(binary.getContentSize())
                .build();

        servletResponse.addHeader(CONTENT_TYPE, binary.getMimeType());
        servletResponse.addHeader(CONTENT_LENGTH, String.valueOf(binary.getContentSize()));
        servletResponse.addHeader("Accept-Ranges", "bytes");
        servletResponse.addHeader(CONTENT_DISPOSITION, contentDisposition.toString());
    }

    servletResponse.addHeader(LINK, "<" + LDP_NAMESPACE + "Resource>;rel=\"type\"");

    if (resource instanceof FedoraBinary) {
        servletResponse.addHeader(LINK, "<" + LDP_NAMESPACE + "NonRDFSource>;rel=\"type\"");
    } else if (resource instanceof Container) {
        servletResponse.addHeader(LINK, "<" + CONTAINER.getURI() + ">;rel=\"type\"");
        if (resource.hasType(LDP_BASIC_CONTAINER)) {
            servletResponse.addHeader(LINK, "<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\"");
        } else if (resource.hasType(LDP_DIRECT_CONTAINER)) {
            servletResponse.addHeader(LINK, "<" + DIRECT_CONTAINER.getURI() + ">;rel=\"type\"");
        } else if (resource.hasType(LDP_INDIRECT_CONTAINER)) {
            servletResponse.addHeader(LINK, "<" + INDIRECT_CONTAINER.getURI() + ">;rel=\"type\"");
        } else {
            servletResponse.addHeader(LINK, "<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\"");
        }
    } else {
        servletResponse.addHeader(LINK, "<" + LDP_NAMESPACE + "RDFSource>;rel=\"type\"");
    }
    if (httpHeaderInject != null) {
        httpHeaderInject.addHttpHeaderToResponseStream(servletResponse, uriInfo, resource());
    }

}
 
开发者ID:fcrepo4,项目名称:fcrepo4,代码行数:47,代码来源:ContentExposingResource.java



注:本文中的org.glassfish.jersey.media.multipart.ContentDisposition类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java JdbcExceptionHelper类代码示例发布时间:2022-05-23
下一篇:
Java ForwardingExecutorService类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap