Example usage for javax.activation MimeType MimeType

List of usage examples for javax.activation MimeType MimeType

Introduction

In this page you can find the example usage for javax.activation MimeType MimeType.

Prototype

public MimeType(String rawdata) throws MimeTypeParseException 

Source Link

Document

Constructor that builds a MimeType from a String.

Usage

From source file:eu.peppol.outbound.HttpPostTestIT.java

@Test
public void testPost() throws Exception {

    InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader()
            .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML);
    assertNotNull(resourceAsStream,/*from  w w  w  .  j av  a  2s.  c o m*/
            "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path");

    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream,
            new MimeType("application/xml"));

    signedMimeMessage.writeTo(System.out);

    CloseableHttpClient httpClient = createCloseableHttpClient();

    HttpPost httpPost = new HttpPost(OXALIS_AS2_URL);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    signedMimeMessage.writeTo(byteArrayOutputStream);

    X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal();
    CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal);
    PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender);

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString());
    httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(),
            new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST")
                    .toString());
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE");
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted
    httpPost.setEntity(
            new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed")));

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL);
    }

    HttpEntity entity = postResponse.getEntity(); // Any results?
    Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200);
    String contents = EntityUtils.toString(entity);

    assertNotNull(contents);
    if (log.isDebugEnabled()) {
        log.debug("Received: \n");
        Header[] allHeaders = postResponse.getAllHeaders();
        for (Header header : allHeaders) {
            log.debug("" + header.getName() + ": " + header.getValue());
        }
        log.debug("\n" + contents);
        log.debug("---------------------------");
    }

    try {

        MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents);
        System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType());

        // Make sure we set content type header for the multipart message (should be multipart/signed)
        String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one
        mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse);
        Enumeration<String> headerlines = mimeMessage.getAllHeaderLines();
        while (headerlines.hasMoreElements()) {
            // Content-Type: multipart/signed;
            // protocol="application/pkcs7-signature";
            // micalg=sha-1;
            // boundary="----=_Part_3_520186210.1399207766925"
            System.out.println("HeaderLine : " + headerlines.nextElement());
        }

        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();
        System.out.println(msg);

    } finally {
        postResponse.close();
    }
}

From source file:eu.fusepool.p3.transformer.client.TransformerClientImpl.java

private void setMimeTypes() {
    HttpURLConnection connection = null;
    try {/*from   w  w w .  j  av  a 2 s.  c om*/
        connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "text/turtle");

        final Parser parser = Parser.getInstance();
        final UriRef transformerRes = new UriRef(uri.toString());
        final Graph graph = parser.parse(connection.getInputStream(), "text/turtle", transformerRes);
        final GraphNode transformerNode = new GraphNode(transformerRes, graph);
        {
            final Iterator<Literal> sifIter = transformerNode.getLiterals(TRANSFORMER.supportedInputFormat);
            while (sifIter.hasNext()) {
                Literal lit = sifIter.next();
                try {
                    supportedInputFormats.add(new MimeType(lit.getLexicalForm()));
                } catch (MimeTypeParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        {
            final Iterator<Literal> sofIter = transformerNode.getLiterals(TRANSFORMER.supportedOutputFormat);
            while (sofIter.hasNext()) {
                Literal lit = sofIter.next();
                try {
                    supportedOutputFormats.add(new MimeType(lit.getLexicalForm()));
                } catch (MimeTypeParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Cannot establish connection to " + uri.toString() + " !", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswTransformProviderTest.java

@Test
public void testMarshalCswRecord() throws Exception {
    when(mockMetacardManager.getTransformerBySchema(CswConstants.CSW_OUTPUT_SCHEMA))
            .thenReturn(mockCswRecordConverter);

    when(mockCswRecordConverter.transform(any(Metacard.class), any(Map.class))).thenReturn(
            new BinaryContentImpl(IOUtils.toInputStream(getRecord()), new MimeType(MediaType.APPLICATION_XML)));

    StringWriter stringWriter = new StringWriter();
    HierarchicalStreamWriter writer = new WstxDriver().createWriter(stringWriter);
    CswTransformProvider provider = new CswTransformProvider(mockMetacardManager, null);
    MarshallingContext context = new TreeMarshaller(writer, null, null);

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);

    provider.marshal(getMetacard(), writer, context);

    // Verify the context arguments were set correctly
    verify(mockMetacardManager, times(1)).getTransformerBySchema(captor.capture());

    String outputSchema = captor.getValue();

    assertThat(outputSchema, is(CswConstants.CSW_OUTPUT_SCHEMA));
}

From source file:org.codice.ddf.security.handler.anonymous.configuration.Configuration.java

public void setMimeType(String mimeType) {
    MimeType mime = null;/*from   ww  w .  ja  v  a  2 s .  c  o  m*/

    try {
        mime = new MimeType(mimeType);
    } catch (MimeTypeParseException e) {
        LOGGER.warn("Failed to create mimetype: {}.", mimeType);
    }

    this.mimeType = mime;
}

From source file:org.apache.isis.core.metamodel.facets.value.blobs.BlobValueSemanticsProvider.java

@Override
protected Blob doRestore(final String data) {
    final int colonIdx = data.indexOf(':');
    final String name = data.substring(0, colonIdx);
    final int colon2Idx = data.indexOf(":", colonIdx + 1);
    final String mimeTypeBase = data.substring(colonIdx + 1, colon2Idx);
    final byte[] bytes = Base64.decodeBase64(data.substring(colon2Idx + 1));
    try {//from  w  ww.j a  va  2s . c  o m
        return new Blob(name, new MimeType(mimeTypeBase), bytes);
    } catch (MimeTypeParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.fusepool.p3.transformer.web.client.server.RootResource.java

private ClosableEntity getEntity(String resourceUri, Set<MimeType> supportedInputFormats) throws IOException {
    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpGet request = new HttpGet(resourceUri);
    request.setHeader("Accept", toAcceptHeaderValue(supportedInputFormats.iterator()));
    final CloseableHttpResponse response = httpclient.execute(request);
    final HttpEntity httpEntity = response.getEntity();
    httpEntity.getContent();/*from   ww  w  .java  2  s . co  m*/
    return new ClosableInputStreamEntity() {

        @Override
        public MimeType getType() {
            try {
                return new MimeType(httpEntity.getContentType().getValue());
            } catch (MimeTypeParseException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        public InputStream getData() throws IOException {
            return httpEntity.getContent();
        }

        @Override
        public void close() throws IOException {
            response.close();
        }
    };
}

From source file:ddf.content.plugin.video.TestVideoThumbnailPlugin.java

private void setUpMockContentItem(final String resource)
        throws IOException, MimeTypeParseException, URISyntaxException {
    mockContentItem = mock(ContentItem.class);

    doReturn(new MimeType("video/mp4")).when(mockContentItem).getMimeType();

    doReturn(new File(getClass().getClassLoader().getResource(resource).toURI())).when(mockContentItem)
            .getFile();//from   ww  w  .  java2  s .c  o  m
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*w  w w  . jav a 2s  .c om*/
public void testAddAttachmentPart() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    AttachmentPart attachment = message.createAttachmentPart();
    message.addAttachmentPart(attachment);
    Iterator it = message.getAttachments();
    assertTrue(it.hasNext());
    assertSame(attachment, it.next());
    assertFalse(it.hasNext());
    // Check that the content type automatically changes to SwA
    if (message.saveRequired()) {
        message.saveChanges();
    }
    String[] contentTypeArray = message.getMimeHeaders().getHeader("Content-Type");
    assertNotNull(contentTypeArray);
    assertEquals(1, contentTypeArray.length);
    MimeType contentType = new MimeType(contentTypeArray[0]);
    assertEquals("multipart/related", contentType.getBaseType());
    assertEquals(messageSet.getVersion().getContentType(), contentType.getParameter("type"));
    assertNotNull(contentType.getParameter("boundary"));
}

From source file:org.apache.james.transport.matchers.HasMimeTypeParameter.java

private Optional<MimeType> getMimeTypeFromMessage(MimeMessage message) throws MessagingException {
    try {//from  ww w.j  av  a  2s .  c  om
        return Optional.of(new MimeType(message.getContentType()));
    } catch (MimeTypeParseException e) {
        LOGGER.warn("Error while parsing message's mimeType {}", message.getContentType(), e);
        return Optional.empty();
    }
}

From source file:ddf.catalog.transformer.resource.ResourceMetacardTransformer.java

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments)
        throws CatalogTransformerException {

    LOGGER.trace("Entering resource ResourceMetacardTransformer.transform");

    if (!isValid(metacard)) {
        throw new CatalogTransformerException(
                "Could not transform metacard to a resource because the metacard is not valid.");
    }//  w  w  w.  j a  v  a  2  s.c  om

    if (StringUtils.isNotEmpty(metacard.getResourceSize())) {
        arguments.put(Metacard.RESOURCE_SIZE, metacard.getResourceSize());
    }

    String id = metacard.getId();
    LOGGER.debug("executing resource request with id '{}'", id);

    final ResourceRequest resourceRequest = new ResourceRequestById(id, arguments);

    ResourceResponse resourceResponse = null;

    String sourceName = metacard.getSourceId();

    if (StringUtils.isBlank(sourceName)) {
        sourceName = catalogFramework.getId();
    }

    String resourceUriAscii = "";
    if (metacard.getResourceURI() != null) {
        resourceUriAscii = metacard.getResourceURI().toASCIIString();
    }

    try {
        resourceResponse = catalogFramework.getResource(resourceRequest, sourceName);
    } catch (IOException e) {
        throw new CatalogTransformerException(
                retrieveResourceFailureMessage(id, sourceName, resourceUriAscii, e.getMessage()), e);
    } catch (ResourceNotFoundException e) {
        throw new CatalogTransformerException(
                retrieveResourceFailureMessage(id, sourceName, resourceUriAscii, e.getMessage()), e);
    } catch (ResourceNotSupportedException e) {
        throw new CatalogTransformerException(
                retrieveResourceFailureMessage(id, sourceName, resourceUriAscii, e.getMessage()), e);
    }

    if (resourceResponse == null) {
        throw new CatalogTransformerException(retrieveResourceFailureMessage(id, sourceName, resourceUriAscii));
    }

    Resource transformedContent = resourceResponse.getResource();
    MimeType mimeType = transformedContent.getMimeType();

    if (mimeType == null) {
        try {
            mimeType = new MimeType(DEFAULT_MIME_TYPE_STR);
            // There is no method to set the MIME type, so in order to set it to our default
            // one, we need to create a new object.
            transformedContent = new ResourceImpl(transformedContent.getInputStream(), mimeType,
                    transformedContent.getName());
        } catch (MimeTypeParseException e) {
            throw new CatalogTransformerException(
                    "Could not create default mime type upon null mimeType, for default mime type '"
                            + DEFAULT_MIME_TYPE_STR + "'.",
                    e);
        }
    }
    LOGGER.debug(
            "Found mime type: '{}' for product of metacard with id: '{}'.\nGetting associated resource from input stream. \n",
            mimeType, id);

    LOGGER.trace("Exiting resource transform for metacard id: '{}'", id);
    return transformedContent;
}