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:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswTransformProviderTest.java

@Test
public void testMarshalOtherSchema() throws Exception {
    when(mockMetacardManager.getTransformerByProperty(TransformerManager.SCHEMA, OTHER_SCHEMA))
            .thenReturn(mockMetacardTransformer);

    when(mockMetacardTransformer.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);
    context.put(CswConstants.TRANSFORMER_LOOKUP_KEY, TransformerManager.SCHEMA);
    context.put(CswConstants.TRANSFORMER_LOOKUP_VALUE, OTHER_SCHEMA);

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

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

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

    String outputSchema = captor.getValue();

    assertThat(outputSchema, is(OTHER_SCHEMA));
}

From source file:org.codice.ddf.catalog.content.plugin.video.TestVideoThumbnailPlugin.java

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

    Metacard mockMetacard = new MetacardImpl();

    doReturn(mockMetacard).when(mockContentItem).getMetacard();

    doReturn(ID).when(mockContentItem).getId();

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

    HashMap<String, Path> contentPaths = new HashMap<>();
    Path tmpPath = Paths.get(getClass().getResource(resource).toURI());
    contentPaths.put(ID, tmpPath);/*from w  ww  .  j  a  v  a 2s.c  o  m*/
    properties = new HashMap<>();
    properties.put(Constants.CONTENT_PATHS, contentPaths);
}

From source file:org.echocat.jomon.net.http.HttpUtils.java

@Nullable
public static MimeType findMimeTypeOf(@Nonnull HttpEntity entity) throws IOException {
    final MimeType mimeType;
    final Header contentTypeHeader = entity.getContentType();
    final String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
    try {//from  ww w  . j  a  v a 2 s. c  o  m
        mimeType = contentType != null ? new MimeType(contentType) : null;
    } catch (final MimeTypeParseException e) {
        throw new IOException("Illegal contentType: " + contentType, e);
    }
    return mimeType;
}

From source file:ddf.mime.mapper.MimeTypeToTransformerMapperImpl.java

private MimeType constructMimeType(String mimeTypeRawEntry) {

    try {/*from  ww  w.  j a  va2s  .c  om*/
        return new MimeType(mimeTypeRawEntry);
    } catch (MimeTypeParseException e) {
        LOGGER.debug("MIME type parse exception constructing MIME type", e);
    }

    return null;
}

From source file:eu.openanalytics.rsb.Util.java

/**
 * Returns the must probable mime type for a file.
 * /*from ww w  .  j a va 2 s. c o  m*/
 * @param file
 * @return {@link eu.openanalytics.rsb.Constants#DEFAULT_MIME_TYPE} if unknown.
 */
public static MimeType getMimeType(final File file) {
    try {
        return new MimeType(getContentType(file));
    } catch (final MimeTypeParseException mtpe) {
        return Constants.DEFAULT_MIME_TYPE;
    }
}

From source file:org.kalypso.model.wspm.pdb.internal.wspm.DocumentConverter.java

private MimeType convertMimeType(final String mimeType) {
    try {//  w  ww.  ja  v a  2s. c  o  m
        if (StringUtils.isBlank(mimeType))
            return null;

        return new MimeType(mimeType);
    } catch (final MimeTypeParseException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.abdera2.common.protocol.ClientResponseImpl.java

public MimeType getContentType() {
    try {/*from w  w  w .  j ava2  s.c o m*/
        String ct = getHeader("Content-Type");
        return ct != null ? new MimeType(ct) : null;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:ddf.catalog.content.data.impl.ContentItemImpl.java

/**
 * An incoming content item where the item's GUID and size should be known.
 *
 * @param id              the {@link ContentItem}'s GUID - can be null
 * @param qualifier       the {@link ContentItem}'s qualifier - can be null
 * @param byteSource      the {@link ContentItem}'s input stream containing its actual data
 * @param mimeTypeRawData the {@link ContentItem}'s mime type
 * @param filename        the {@link ContentItem}'s file name - can be null
 * @param size            the {@link ContentItem}'s file size
 * @param metacard        the {@link ContentItem}'s associated metacard
 *//*from  ww w .j a va2 s. c  o  m*/
public ContentItemImpl(String id, String qualifier, ByteSource byteSource, String mimeTypeRawData,
        String filename, long size, Metacard metacard) {
    this.byteSource = byteSource;
    this.id = id;
    this.qualifier = qualifier;
    this.mimeType = null;
    this.size = size;
    if (filename != null) {
        this.filename = filename;
    } else {
        this.filename = DEFAULT_FILE_NAME;
    }
    this.metacard = metacard;
    this.mimeTypeRawData = DEFAULT_MIME_TYPE;
    if (StringUtils.isNotBlank(mimeTypeRawData)) {
        this.mimeTypeRawData = mimeTypeRawData;
    }
    try {
        this.mimeType = new MimeType(this.mimeTypeRawData);
    } catch (MimeTypeParseException e) {
        LOGGER.debug("Unable to create MimeType from raw data " + mimeTypeRawData);
    }
    try {
        if (StringUtils.isNotBlank(this.qualifier)) {
            uri = new URI(CONTENT_SCHEME, this.id, this.qualifier);
        } else {
            uri = new URI(CONTENT_SCHEME, this.id, null);
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Unable to create content URI.", e);
    }
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender,
        PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData,
        PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) {

    if (peppolEndpointData.getCommonName() == null) {
        throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData);
    }//from www  .ja va  2  s . c om
    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = null;
    Mic mic = null;
    try {
        MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream,
                new MimeType("application/xml"));
        mic = MimeMessageHelper.calculateMic(mimeBodyPart);
        log.debug("Outbound MIC is : " + mic.toString());
        signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart);
    } catch (MimeTypeParseException e) {
        throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e);
    }

    String endpointAddress = peppolEndpointData.getUrl().toExternalForm();
    HttpPost httpPost = new HttpPost(endpointAddress);

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

    } catch (Exception e) {
        throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream");
    }

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString());
    try {
        httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(),
                PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString());
    } catch (InvalidAs2SystemIdentifierException e) {
        throw new IllegalArgumentException(
                "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData);
    }

    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no");
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS");

    TransmissionId transmissionId = new TransmissionId();
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted.
    // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header
    try {
        String contentType = signedMimeMessage.getContentType();
        ContentType ct = ContentType.create(contentType);
        httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct));
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage());
    }

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        CloseableHttpClient httpClient = createCloseableHttpClient();
        log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type "
                + peppolDocumentTypeId);
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(),
                e);
    }

    if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode()
                + " from " + endpointAddress);
        throw handleFailedRequest(postResponse);
    }

    // handle normal HTTP OK response
    log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress
            + " returned HTTP OK, verify MDN response");
    MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData);

    // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl
    MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
    Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields();
    String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST);
    if (messageDigestAsBase64 == null) {
        messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes()));
    }
    String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP);
    Date receptionTimeStamp = null;
    if (receptionTimeStampAsString != null) {
        receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString);
    } else {
        receptionTimeStamp = new Date();
    }

    // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence
    DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString());

    @NotNull
    As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence(
            EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage,
            new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types
            new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types
            documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64),
            transmissionId);

    ByteArrayOutputStream evidenceBytes;
    try {
        evidenceBytes = new ByteArrayOutputStream();
        IOUtils.copy(evidence.getInputStream(), evidenceBytes);
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to transform transport evidence to byte array." + e.getMessage(), e);
    }

    return new SendResult(transmissionId, evidenceBytes.toByteArray());
}

From source file:org.codice.ddf.spatial.ogc.catalog.resource.impl.TestResourceReader.java

/**
 * Tests the case in which the Resource in the ResourceResponse returned by the
 * URLResourceReader has a text/html mime type.
 *//*ww  w .ja v a 2 s. co m*/
@Test
public void testRetrieveResourceMimeTypeTextHtml() throws Exception {
    // Setup
    String httpUriStr = HTTP_SCHEME_PLUS_SEP + MOCK_HTTP_SERVER_HOST + ":" + MOCK_HTTP_SERVER_PORT
            + MOCK_HTTP_SERVER_PATH;

    URI uri = new URI(httpUriStr);
    Response mockResponse = getMockResponse();
    setupMockWebClient(mockResponse);
    ResourceResponse mockResourceResponse = getMockResourceResponse(new MimeType("application/octet-stream"));
    URLResourceReader mockUrlResourceReader = getMockUrlResourceReader(uri, mockResourceResponse);
    setupMockTika(MediaType.TEXT_HTML);
    OgcUrlResourceReader resourceReader = new OgcUrlResourceReader(mockUrlResourceReader, mockTika);

    HashMap<String, Serializable> arguments = new HashMap<String, Serializable>();

    // Perform Test
    ResourceResponse resourceResponse = resourceReader.retrieveResource(uri, arguments);

    // Verify
    StringWriter writer = new StringWriter();
    IOUtils.copy(resourceResponse.getResource().getInputStream(), writer, MOCK_HTTP_SERVER_ENCODING);
    String responseString = writer.toString();

    LOGGER.info("Response " + responseString);

    assertThat(responseString, is("<html><script type=\"text/javascript\">window.location.replace(\""
            + httpUriStr + "\");</script></html>"));
}