javax.activation.MimeType Java Examples

The following examples show how to use javax.activation.MimeType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FallbackMimeTypeProvider.java    From ogham with Apache License 2.0 6 votes vote down vote up
private MimeType detect(ByteArrayInputStream copy) {
	MimeType mimetype = null;
	for (MimeTypeProvider provider : providers) {
		try {
			LOG.debug("Trying to get mime type from stream using {}", provider);
			mimetype = provider.detect(copy);
			LOG.debug("{} has detected mime type {} from stream", provider, mimetype);
			break;
		} catch (MimeTypeDetectionException e) {
			// try next one => move read cursor to beginning
			copy.reset();
			LOG.debug("{} could not detect mime type from stream. Cause: {}", provider, e.getMessage(), e);
		}
	}
	return mimetype;
}
 
Example #2
Source File: DownloadServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String registerDownloadData( String temporaryFileName, MimeType mimeType, String downloadName, HttpSession session) {
	Map<String, FileData> downloadData = getOrCreateDownloadDataMap( session);
	
	// Create a random UUID
	UUID uuid = UUID.randomUUID();
	
	// For the very rare possibility of duplicate UUIDs in the map, verify UUID and create new one if necessary
	while( downloadData.containsKey( uuid.toString())) {
		if( logger.isInfoEnabled())
			logger.info( "UUID " + uuid.toString() + " already used - renewing UUID");
		
		uuid = UUID.randomUUID();
	}
	
	if( logger.isDebugEnabled()) {
		logger.debug( "Registering download data (temp file: " + temporaryFileName + ", MIME type: " + mimeType + ", download name: " + downloadName + ", ID: " + uuid);
	}
	
	FileData fileData = new FileData( temporaryFileName, mimeType, downloadName);
	downloadData.put( uuid.toString(), fileData);
	
	return uuid.toString();
}
 
Example #3
Source File: Util.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static MimeType calcExpectedMediaType(AnnotationSource primarySource,
                    ModelBuilder builder ) {
    XmlMimeType xmt = primarySource.readAnnotation(XmlMimeType.class);
    if(xmt==null)
        return null;

    try {
        return new MimeType(xmt.value());
    } catch (MimeTypeParseException e) {
        builder.reportError(new IllegalAnnotationException(
            Messages.ILLEGAL_MIME_TYPE.format(xmt.value(),e.getMessage()),
            xmt
        ));
        return null;
    }
}
 
Example #4
Source File: UrlRewriteStreamFilterFactory.java    From knox with Apache License 2.0 6 votes vote down vote up
@Deprecated
public static InputStream create(
    MimeType type,
    String name,
    InputStream stream,
    UrlRewriter rewriter,
    Resolver resolver,
    UrlRewriter.Direction direction,
    UrlRewriteFilterContentDescriptor config )
        throws IOException {
  UrlRewriteStreamFilter filter = create(type, name);
  String charset = MimeTypes.getCharset( type, StandardCharsets.UTF_8.name() );
  final InputStream filteredStream;
  if( filter != null ) {
    filteredStream = filter.filter( stream, charset, rewriter, resolver, direction, config );
  } else {
    filteredStream = stream;
  }
  return filteredStream;
}
 
Example #5
Source File: XmlSchemaGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes a type attribute (if the referenced type is a global type)
 * or writes out the definition of the anonymous type in place (if the referenced
 * type is not a global type.)
 *
 * Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
 *
 * ComplexTypeHost and SimpleTypeHost don't share an api for creating
 * and attribute in a type-safe way, so we will compromise for now and
 * use _attribute().
 */
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
    // ID / IDREF handling
    switch(typeRef.getSource().id()) {
    case ID:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
        return;
    case IDREF:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
        return;
    case NONE:
        // no ID/IDREF, so continue on and generate the type
        break;
    default:
        throw new IllegalStateException();
    }

    // MTOM handling
    MimeType mimeType = typeRef.getSource().getExpectedMimeType();
    if( mimeType != null ) {
        th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
    }

    // ref:swaRef handling
    if(generateSwaRefAdapter(typeRef)) {
        th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
        return;
    }

    // type name override
    if(typeRef.getSource().getSchemaType()!=null) {
        th._attribute(refAttName,typeRef.getSource().getSchemaType());
        return;
    }

    // normal type generation
    writeTypeRef(th, typeRef.getTarget(), refAttName);
}
 
Example #6
Source File: MappingJacksonResponseParser.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private static MimeType defaultMimeType() {
	try {
		return new MimeType("application", "json");
	} catch (MimeTypeParseException o_O) {
		throw new IllegalArgumentException(o_O);
	}
}
 
Example #7
Source File: AbstractProtocolTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Match content type against expected type
 */
protected void matchResponseContentType(String expectedType) {
	String fullType = getResponseContentType();
	if (fullType == null) {
		assertNull(expectedType);
	} else {
		try {
			MimeType ctype = new MimeType(fullType);
			assertTrue("Types "+fullType+" and "+expectedType+" do not match", ctype.match(expectedType));
		} catch (MimeTypeParseException e) {
			assertEquals(expectedType, fullType);
		}

	}
}
 
Example #8
Source File: TypeUseImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public TypeUseImpl(CNonElement itemType, boolean collection, ID id, MimeType expectedMimeType, CAdapter adapter) {
    this.coreType = itemType;
    this.collection = collection;
    this.id = id;
    this.expectedMimeType = expectedMimeType;
    this.adapter = adapter;
}
 
Example #9
Source File: TypeUseImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public TypeUseImpl(CNonElement itemType, boolean collection, ID id, MimeType expectedMimeType, CAdapter adapter) {
    this.coreType = itemType;
    this.collection = collection;
    this.id = id;
    this.expectedMimeType = expectedMimeType;
    this.adapter = adapter;
}
 
Example #10
Source File: MimeTypeWhitelistServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean isMimeTypeWhitelisted(final String mimeTypeString) {
	try {
		final MimeType mimeType = new MimeType(mimeTypeString);
		return isMimeTypeWhitelisted(mimeType);
	} catch (MimeTypeParseException e) {
		return false;
	}
}
 
Example #11
Source File: AsynchronousTransformerTest.java    From p3-batchrefine with Apache License 2.0 5 votes vote down vote up
private Response doRequest(String input, String transform, String format,
                             MimeType contentType) throws Exception {
      String transformURI = fServers.transformURI(input + "-" + transform + ".json").toString();

      Response response = RestAssured.given()
              .queryParam("refinejson", transformURI)
              .header("Accept", contentType.toString() + ";q=1.0")
              .contentType("text/csv")
              .content(contentsAsBytes("inputs", input, "csv"))
              .when().post();

      Assert.assertEquals(HttpStatus.SC_ACCEPTED, response.getStatusCode());

      String location = response.getHeader("location");
      Assert.assertTrue(location != null);

/* Polls until ready. */
      long start = System.currentTimeMillis();
      do {
          response = RestAssured.given()
                  .header("Accept", "text/turtle")
                  .header("Content-Type", "text/turtle")
                  .when().get(location);

          if (System.currentTimeMillis() - start >= ASYNC_TIMEOUT) {
              Assert.fail("Asynchronous call timed out.");
          }

          Thread.sleep(100);

      } while (response.statusCode() == HttpStatus.SC_ACCEPTED);

      return response;
  }
 
Example #12
Source File: InlineImageTranslatorTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws MimeTypeDetectionException, MimeTypeParseException {
	when(mimeTypeProvider.detect(any(InputStream.class))).thenReturn(new MimeType("image/gif"));
	SequentialIdGenerator idGenerator = new SequentialIdGenerator();
	ImageInliner inliner = new EveryImageInliner(
			new JsoupAttachImageInliner(idGenerator),
			new JsoupBase64ImageInliner(), 
			new RegexAttachBackgroudImageInliner(idGenerator),
			new RegexBase64BackgroundImageInliner());
	Map<String, List<String>> lookups = new HashMap<>();
	lookups.put("classpath", asList("classpath:", ""));
	RelativePathResolver relativePathResolver = new LookupAwareRelativePathResolver(lookups);
	ResourceResolver resourceResolver = new RelativeResolver(new ClassPathResolver("classpath:", ""), SOURCE_FOLDER);
	translator = new InlineImageTranslator(inliner, resourceResolver, mimeTypeProvider, relativePathResolver);
}
 
Example #13
Source File: FallbackMimeTypeProvider.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public MimeType getMimeType(File file) throws MimeTypeDetectionException {
	for (MimeTypeProvider provider : providers) {
		try {
			LOG.debug("Trying to get mime type for file {} using {}", file, provider);
			MimeType mimetype = provider.getMimeType(file);
			LOG.debug("{} has detected mime type {} for file {}", provider, mimetype, file);
			return mimetype;
		} catch (MimeTypeDetectionException e) {
			// nothing to do => try next one
			LOG.debug("{} could not detect mime type for file {}. Cause: {}", provider, file, e.getMessage(), e);
		}
	}
	throw new NoMimetypeDetectorException("No mimetype provider could provide the mimetype for the file " + file);
}
 
Example #14
Source File: SimpleMimetypeDetectionBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
private MimeTypeProvider validateProvider(MimeTypeProvider provider) {
	String[] allowed = allowedMimetypesValueBuilder.getValue(new String[0]);
	if (allowed.length <= 0) {
		// no validation
		return provider;
	}
	Predicate<MimeType> merged = m -> true;
	for (int i=0 ; i<allowed.length ; i++) {
		Predicate<MimeType> predicate = toPredicate(allowed[i]);
		merged = merged.and(predicate);
	}
	return new AllowedMimetypeDecorator(merged, provider);
}
 
Example #15
Source File: XmlSchemaGenerator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes a type attribute (if the referenced type is a global type)
 * or writes out the definition of the anonymous type in place (if the referenced
 * type is not a global type.)
 *
 * Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
 *
 * ComplexTypeHost and SimpleTypeHost don't share an api for creating
 * and attribute in a type-safe way, so we will compromise for now and
 * use _attribute().
 */
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
    // ID / IDREF handling
    switch(typeRef.getSource().id()) {
    case ID:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
        return;
    case IDREF:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
        return;
    case NONE:
        // no ID/IDREF, so continue on and generate the type
        break;
    default:
        throw new IllegalStateException();
    }

    // MTOM handling
    MimeType mimeType = typeRef.getSource().getExpectedMimeType();
    if( mimeType != null ) {
        th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
    }

    // ref:swaRef handling
    if(generateSwaRefAdapter(typeRef)) {
        th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
        return;
    }

    // type name override
    if(typeRef.getSource().getSchemaType()!=null) {
        th._attribute(refAttName,typeRef.getSource().getSchemaType());
        return;
    }

    // normal type generation
    writeTypeRef(th, typeRef.getTarget(), refAttName);
}
 
Example #16
Source File: XmlSchemaGenerator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes a type attribute (if the referenced type is a global type)
 * or writes out the definition of the anonymous type in place (if the referenced
 * type is not a global type.)
 *
 * Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
 *
 * ComplexTypeHost and SimpleTypeHost don't share an api for creating
 * and attribute in a type-safe way, so we will compromise for now and
 * use _attribute().
 */
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
    // ID / IDREF handling
    switch(typeRef.getSource().id()) {
    case ID:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
        return;
    case IDREF:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
        return;
    case NONE:
        // no ID/IDREF, so continue on and generate the type
        break;
    default:
        throw new IllegalStateException();
    }

    // MTOM handling
    MimeType mimeType = typeRef.getSource().getExpectedMimeType();
    if( mimeType != null ) {
        th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
    }

    // ref:swaRef handling
    if(generateSwaRefAdapter(typeRef)) {
        th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
        return;
    }

    // type name override
    if(typeRef.getSource().getSchemaType()!=null) {
        th._attribute(refAttName,typeRef.getSource().getSchemaType());
        return;
    }

    // normal type generation
    writeTypeRef(th, typeRef.getTarget(), refAttName);
}
 
Example #17
Source File: MimeTypedTransducer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeLeafElement(XMLSerializer w, Name tagName, V o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
    MimeType old = w.setExpectedMimeType(expectedMimeType);
    try {
        core.writeLeafElement(w, tagName, o, fieldName);
    } finally {
        w.setExpectedMimeType(old);
    }
}
 
Example #18
Source File: SynchronousTransformer.java    From p3-batchrefine with Apache License 2.0 5 votes vote down vote up
@Override
public Entity transform(HttpRequestEntity entity) throws IOException {
    logMessage(entity.getRequest());

    final HttpRequestEntity request = cast(entity);

    final ImmutablePair<MimeType, Properties> options = exporterOptions(request);
    options.right.putAll(transformerConfig);
    final File input = downloadInput(entity);
    final File output = File.createTempFile("reply", "tmp");

    final ITransformEngine engine = getEngine();

    return new WritingEntity() {
        @Override
        public void writeData(OutputStream out) throws IOException {
            try {
                // Can't allow more than one transform at a time as OpenRefine is not
                // designed for that.
                synchronized (SynchronousTransformer.this) {
                    engine.transform(input.toURI(), fetchTransform(request), output.toURI(),
                            options.right);
                }

                try (FileInputStream stream = new FileInputStream(output)) {
                    IOUtils.copy(stream, out);
                }
            } finally {
                input.delete();
                output.delete();
            }
        }

        @Override
        public MimeType getType() {
            return options.left;
        }
    };
}
 
Example #19
Source File: MimeTypedTransducer.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public CharSequence print(V o) throws AccessorException {
    XMLSerializer w = XMLSerializer.getInstance();
    MimeType old = w.setExpectedMimeType(expectedMimeType);
    try {
        return core.print(o);
    } finally {
        w.setExpectedMimeType(old);
    }
}
 
Example #20
Source File: MimeTypedTransducer.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeText(XMLSerializer w, V o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
    MimeType old = w.setExpectedMimeType(expectedMimeType);
    try {
        core.writeText(w, o, fieldName);
    } finally {
        w.setExpectedMimeType(old);
    }
}
 
Example #21
Source File: XmlSchemaGenerator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes a type attribute (if the referenced type is a global type)
 * or writes out the definition of the anonymous type in place (if the referenced
 * type is not a global type.)
 *
 * Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
 *
 * ComplexTypeHost and SimpleTypeHost don't share an api for creating
 * and attribute in a type-safe way, so we will compromise for now and
 * use _attribute().
 */
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
    // ID / IDREF handling
    switch(typeRef.getSource().id()) {
    case ID:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
        return;
    case IDREF:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
        return;
    case NONE:
        // no ID/IDREF, so continue on and generate the type
        break;
    default:
        throw new IllegalStateException();
    }

    // MTOM handling
    MimeType mimeType = typeRef.getSource().getExpectedMimeType();
    if( mimeType != null ) {
        th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
    }

    // ref:swaRef handling
    if(generateSwaRefAdapter(typeRef)) {
        th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
        return;
    }

    // type name override
    if(typeRef.getSource().getSchemaType()!=null) {
        th._attribute(refAttName,typeRef.getSource().getSchemaType());
        return;
    }

    // normal type generation
    writeTypeRef(th, typeRef.getTarget(), refAttName);
}
 
Example #22
Source File: DataSourceSource.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public DataSourceSource(DataSource source) throws MimeTypeParseException {
    this.source = source;

    String ct = source.getContentType();
    if(ct==null) {
        charset = null;
    } else {
        MimeType mimeType = new MimeType(ct);
        this.charset = mimeType.getParameter("charset");
    }
}
 
Example #23
Source File: XmlSchemaGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes a type attribute (if the referenced type is a global type)
 * or writes out the definition of the anonymous type in place (if the referenced
 * type is not a global type.)
 *
 * Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
 *
 * ComplexTypeHost and SimpleTypeHost don't share an api for creating
 * and attribute in a type-safe way, so we will compromise for now and
 * use _attribute().
 */
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
    // ID / IDREF handling
    switch(typeRef.getSource().id()) {
    case ID:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
        return;
    case IDREF:
        th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
        return;
    case NONE:
        // no ID/IDREF, so continue on and generate the type
        break;
    default:
        throw new IllegalStateException();
    }

    // MTOM handling
    MimeType mimeType = typeRef.getSource().getExpectedMimeType();
    if( mimeType != null ) {
        th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
    }

    // ref:swaRef handling
    if(generateSwaRefAdapter(typeRef)) {
        th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
        return;
    }

    // type name override
    if(typeRef.getSource().getSchemaType()!=null) {
        th._attribute(refAttName,typeRef.getSource().getSchemaType());
        return;
    }

    // normal type generation
    writeTypeRef(th, typeRef.getTarget(), refAttName);
}
 
Example #24
Source File: ToDoItemIntegTest.java    From isis-app-todoapp with Apache License 2.0 5 votes vote down vote up
@Test
public void happyCase() throws Exception {

    final byte[] bytes = "{\"foo\": \"bar\"}".getBytes(Charset.forName("UTF-8"));
    final Blob newAttachment = new Blob("myfile.json", new MimeType("application/json"), bytes);

    // when
    wrap(toDoItem).setAttachment(newAttachment);

    // then
    assertThat(wrap(toDoItem).getAttachment()).isEqualTo(newAttachment);
}
 
Example #25
Source File: RawTypeSet.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public MimeType getExpectedMimeType() {
    for( Ref t : refs ) {
        MimeType mt = t.getExpectedMimeType();
        if(mt!=null)    return mt;
    }
    return null;
}
 
Example #26
Source File: AsynchronousTransformerTest.java    From p3-batchrefine with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransform() throws Exception {
    File reference = findAndCopy("outputs/" + fInput + "_" + fTransform
            + "." + fFormat);
    MimeType mime = mapContentType(fFormat);
    Response response = doRequest(fInput, fTransform, fFormat, mime);
    File output = EngineTestUtils
            .toFile(response.getBody().asInputStream());
    assertEquals(reference, output, mime);
}
 
Example #27
Source File: MimeTypedTransducer.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeLeafElement(XMLSerializer w, Name tagName, V o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
    MimeType old = w.setExpectedMimeType(expectedMimeType);
    try {
        core.writeLeafElement(w, tagName, o, fieldName);
    } finally {
        w.setExpectedMimeType(old);
    }
}
 
Example #28
Source File: CElementPropertyInfo.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public CElementPropertyInfo(String name, CollectionMode collection, ID id, MimeType expectedMimeType, XSComponent source,
                            CCustomizations customizations, Locator locator, boolean required) {
    super(name, collection.col, source, customizations, locator);
    this.required = required;
    this.id = id;
    this.expectedMimeType = expectedMimeType;
    this.isValueList = collection.val;
}
 
Example #29
Source File: RawTypeSet.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public MimeType getExpectedMimeType() {
    for( Ref t : refs ) {
        MimeType mt = t.getExpectedMimeType();
        if(mt!=null)    return mt;
    }
    return null;
}
 
Example #30
Source File: RawTypeSet.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public MimeType getExpectedMimeType() {
    for( Ref t : refs ) {
        MimeType mt = t.getExpectedMimeType();
        if(mt!=null)    return mt;
    }
    return null;
}