Search in sources :

Example 31 with MimeType

use of javax.activation.MimeType in project ddf by codice.

the class RESTEndpoint method createMetacard.

@POST
@Path("/metacard")
public Response createMetacard(MultipartBody multipartBody, @Context UriInfo requestUriInfo, @QueryParam("transform") String transformerParam) {
    LOGGER.trace("ENTERING: createMetacard");
    String contentUri = multipartBody.getAttachmentObject("contentUri", String.class);
    LOGGER.debug("contentUri = {}", contentUri);
    InputStream stream = null;
    String filename = null;
    String contentType = null;
    Response response = null;
    String transformer = DEFAULT_METACARD_TRANSFORMER;
    if (transformerParam != null) {
        transformer = transformerParam;
    }
    Attachment contentPart = multipartBody.getAttachment(FILE_ATTACHMENT_CONTENT_ID);
    if (contentPart != null) {
        // Content-Type: application/json;id=geojson
        if (contentPart.getContentType() != null) {
            contentType = contentPart.getContentType().toString();
        }
        // at the beginning
        try {
            stream = contentPart.getDataHandler().getInputStream();
            if (stream != null && stream.available() == 0) {
                stream.reset();
            }
        } catch (IOException e) {
            LOGGER.info("IOException reading stream from file attachment in multipart body", e);
        }
    } else {
        LOGGER.debug("No file contents attachment found");
    }
    MimeType mimeType = null;
    if (contentType != null) {
        try {
            mimeType = new MimeType(contentType);
        } catch (MimeTypeParseException e) {
            LOGGER.debug("Unable to create MimeType from raw data {}", contentType);
        }
    } else {
        LOGGER.debug("No content type specified in request");
    }
    try {
        Metacard metacard = generateMetacard(mimeType, "assigned-when-ingested", stream, null);
        String metacardId = metacard.getId();
        LOGGER.debug("Metacard {} created", metacardId);
        LOGGER.debug("Transforming metacard {} to {} to be able to return it to client", metacardId, transformer);
        final BinaryContent content = catalogFramework.transform(metacard, transformer, null);
        LOGGER.debug("Metacard to {} transform complete for {}, preparing response.", transformer, metacardId);
        Response.ResponseBuilder responseBuilder = Response.ok(content.getInputStream(), content.getMimeTypeValue());
        response = responseBuilder.build();
    } catch (MetacardCreationException | CatalogTransformerException e) {
        throw new ServerErrorException("Unable to create metacard", Status.BAD_REQUEST);
    }
    LOGGER.trace("EXITING: createMetacard");
    return response;
}
Also used : MimeTypeParseException(javax.activation.MimeTypeParseException) MetacardCreationException(ddf.catalog.data.MetacardCreationException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) BinaryContent(ddf.catalog.data.BinaryContent) MimeType(javax.activation.MimeType) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) CreateResponse(ddf.catalog.operation.CreateResponse) Metacard(ddf.catalog.data.Metacard) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 32 with MimeType

use of javax.activation.MimeType in project ddf by codice.

the class TestXmlResponseQueueTransformer method testMimeTypeInitException.

@Test(expected = ExceptionInInitializerError.class)
public void testMimeTypeInitException() throws IOException, CatalogTransformerException, XmlPullParserException, MimeTypeParseException {
    SourceResponse response = givenSourceResponse(new MetacardStub("source1", "id1"));
    PrintWriterProvider pwp = new PrintWriterProviderImpl();
    MetacardMarshaller mockMetacardMarshaller = mock(MetacardMarshaller.class);
    MimeType mockMimeType = mock(MimeType.class);
    doThrow(new MimeTypeParseException("")).when(mockMimeType).setSubType(anyString());
    XmlResponseQueueTransformer xrqt = new XmlResponseQueueTransformer(parser, FJP, pwp, mockMetacardMarshaller, mockMimeType);
    xrqt.setThreshold(2);
    BinaryContent bc = xrqt.transform(response, null);
// then exception
}
Also used : MimeTypeParseException(javax.activation.MimeTypeParseException) PrintWriterProvider(ddf.catalog.transformer.api.PrintWriterProvider) SourceResponse(ddf.catalog.operation.SourceResponse) MetacardMarshaller(ddf.catalog.transformer.api.MetacardMarshaller) PrintWriterProviderImpl(ddf.catalog.transformer.xml.PrintWriterProviderImpl) XmlResponseQueueTransformer(ddf.catalog.transformer.xml.XmlResponseQueueTransformer) BinaryContent(ddf.catalog.data.BinaryContent) MimeType(javax.activation.MimeType) Test(org.junit.Test)

Example 33 with MimeType

use of javax.activation.MimeType in project morphia by mongodb.

the class CustomConvertersTest method mimeType.

@Test
public void mimeType() throws UnknownHostException, MimeTypeParseException {
    getMorphia().map(MimeTyped.class);
    getDs().ensureIndexes();
    MimeTyped entity = new MimeTyped();
    entity.name = "test name";
    //MimeTypeParseException
    entity.mimeType = new MimeType("text/plain");
    final DBObject dbObject = getMorphia().toDBObject(entity);
    assertEquals("text/plain", dbObject.get("mimeType"));
    // FAILS WITH ERROR HERE
    getDs().save(entity);
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) MimeType(javax.activation.MimeType) Test(org.junit.Test)

Example 34 with MimeType

use of javax.activation.MimeType in project Xponents by OpenSextant.

the class XText method convertChildren.

/**
     * Save children objects for a given ConvertedDocument to a location....
     * convert those items immediately, saving the Parent metadata along with
     * them. You should have setParent already
     *
     * @param parentDoc
     *            parent conversion
     * @throws IOException
     *             on err
     */
public void convertChildren(ConvertedDocument parentDoc) throws IOException {
    if (parentDoc.is_webArchive) {
        //
        return;
    }
    parentDoc.evalParentChildContainer();
    FileUtility.makeDirectory(parentDoc.parentContainer);
    String targetPath = parentDoc.parentContainer.getAbsolutePath();
    for (Content child : parentDoc.getRawChildren()) {
        if (child.content == null) {
            log.error("Attempted to write out child object with no content {}", child.id);
            continue;
        }
        OutputStream io = null;
        try {
            // We just assume for now Child ID is filename.
            // Alternatively, child.meta.getProperty(
            // ConvertedDocument.CHILD_ENTRY_KEY )
            // same result, just more verbose.
            //
            File childFile = new File(FilenameUtils.concat(targetPath, child.id));
            io = new FileOutputStream(childFile);
            IOUtils.write(child.content, io);
            ConvertedDocument childConv = convertFile(childFile, parentDoc);
            if (childConv != null) {
                if (childConv.is_converted) {
                    // Push down all child metadata down to ConvertedDoc
                    for (String k : child.meta.stringPropertyNames()) {
                        String val = child.meta.getProperty(k);
                        childConv.addUserProperty(k, val);
                    }
                    // Save cached version once again.
                    childConv.saveBuffer(new File(childConv.textpath));
                }
                if (child.mimeType != null) {
                    try {
                        childConv.setMimeType(new MimeType(child.mimeType));
                    } catch (MimeTypeParseException e) {
                        log.warn("Invalid mime type encountered: {} ignoring.", child.mimeType);
                    }
                }
                parentDoc.addChild(childConv);
            }
        } catch (Exception err) {
            log.error("Failed to write out child {}, but will continue with others", child.id, err);
        } finally {
            if (io != null) {
                io.close();
            }
        }
    }
}
Also used : MimeTypeParseException(javax.activation.MimeTypeParseException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) MimeType(javax.activation.MimeType) ConfigException(org.opensextant.ConfigException) IOException(java.io.IOException) MimeTypeParseException(javax.activation.MimeTypeParseException)

Example 35 with MimeType

use of javax.activation.MimeType in project Xponents by OpenSextant.

the class MessageConverterTest method complexEmailTest.

@Test
public void complexEmailTest() throws Exception {
    MessageConverter conv = new MessageConverter();
    ConvertedDocument doc = conv.convert(TEST_FILE);
    Assert.assertEquals((MESSAGE_BODY + MESSAGE_BOUNDARY).trim(), doc.getText());
    Assert.assertEquals(5, doc.getRawChildren().size());
    final HashMap<String, Content> children = new HashMap<String, Content>();
    for (final Content child : doc.getRawChildren()) {
        children.put(child.id, child);
    }
    Content text_attach = children.get("xtext-embedded-attached-text.txt");
    Assert.assertNotNull("text attachment was not found, available attachments are: " + children.keySet(), text_attach);
    String orig_text_attach = IOUtils.toString(getClass().getResourceAsStream("xtext-embedded-attached-text.txt"), "UTF-8");
    String sep = System.getProperty("line.separator");
    if (!"\r\n".equals(sep)) {
        orig_text_attach = orig_text_attach.replaceAll(sep, "\r\n");
    }
    Assert.assertEquals("text/plain", new MimeType(text_attach.mimeType).getBaseType());
    Assert.assertEquals(orig_text_attach, new String(text_attach.content, text_attach.encoding));
    Assert.assertEquals("A686FA7D9F4FB64E99601455209639C5@imc.mitre.org", text_attach.meta.getProperty(CONTENT_ID));
    Assert.assertEquals("attachment", text_attach.meta.getProperty(CONTENT_DISPOSITION));
    Content html_attach = children.get("word_doc_as_html.htm");
    Assert.assertNotNull("Embedded HTML was not found.", html_attach);
    Assert.assertEquals("text/html", new MimeType(html_attach.mimeType).getBaseType());
    Assert.assertEquals("64B706D14F6CAF4598A5A756E2E763A0@imc.mitre.org", html_attach.meta.getProperty(CONTENT_ID));
    Assert.assertEquals("attachment", html_attach.meta.getProperty(CONTENT_DISPOSITION));
    Content word_attach = children.get("doc_with_embedded_geocoded_image2.docx");
    Assert.assertNotNull("Doc with geocoded image was not found.", word_attach);
    Assert.assertEquals("application/vnd.openxmlformats-officedocument.wordprocessingml.document", new MimeType(word_attach.mimeType).getBaseType());
    Assert.assertEquals("3ED3B89ABF3D1840B551B527B4DA054D@imc.mitre.org", word_attach.meta.getProperty(CONTENT_ID));
    Assert.assertEquals("attachment", word_attach.meta.getProperty(CONTENT_DISPOSITION));
    Content jpeg_attach = children.get("android_photo_with_gps1.jpeg");
    Assert.assertNotNull("Photo with attached image was not found.", jpeg_attach);
    Assert.assertEquals("image/jpeg", new MimeType(jpeg_attach.mimeType).getBaseType());
    Assert.assertEquals("485710da-7b60-461a-a566-0ad2e0a14b82@imc.mitre.org", jpeg_attach.meta.getProperty(CONTENT_ID));
    Assert.assertEquals("inline", jpeg_attach.meta.getProperty(CONTENT_DISPOSITION));
    Content htmlbody = null;
    for (final Content child : doc.getRawChildren()) {
        if ("true".equals(child.meta.getProperty(MessageConverter.MAIL_KEY_PREFIX + "html-body"))) {
            Assert.assertNull("multiple html bodies found", htmlbody);
            Assert.assertEquals("text/html", new MimeType(child.mimeType).getBaseType());
            Assert.assertEquals("BEA4D58835C6A342B10D665B40F9D105@imc.mitre.org", child.meta.getProperty(CONTENT_ID));
            htmlbody = child;
        }
    }
    Assert.assertNotNull("html body was not found", htmlbody);
}
Also used : HashMap(java.util.HashMap) Content(org.opensextant.xtext.Content) MessageConverter(org.opensextant.xtext.converters.MessageConverter) ConvertedDocument(org.opensextant.xtext.ConvertedDocument) MimeType(javax.activation.MimeType) Test(org.junit.Test)

Aggregations

MimeType (javax.activation.MimeType)67 Test (org.junit.Test)38 Metacard (ddf.catalog.data.Metacard)21 URI (java.net.URI)14 HashMap (java.util.HashMap)14 MimeTypeParseException (javax.activation.MimeTypeParseException)14 MimeTypeToTransformerMapper (ddf.mime.MimeTypeToTransformerMapper)13 BundleContext (org.osgi.framework.BundleContext)13 ServiceReference (org.osgi.framework.ServiceReference)13 CatalogFramework (ddf.catalog.CatalogFramework)10 ResourceResponse (ddf.catalog.operation.ResourceResponse)10 Serializable (java.io.Serializable)9 Resource (ddf.catalog.resource.Resource)8 IOException (java.io.IOException)8 File (java.io.File)7 Matchers.anyString (org.mockito.Matchers.anyString)7 MetacardCreationException (ddf.catalog.data.MetacardCreationException)6 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)6 Response (javax.ws.rs.core.Response)6 BinaryContentImpl (ddf.catalog.data.impl.BinaryContentImpl)5