Search in sources :

Example 36 with MimeType

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

the class TestCswQueryResponseTransformer method testMarshalAcknowledgementWithFailedTransforms.

@Test
public void testMarshalAcknowledgementWithFailedTransforms() throws WebApplicationException, IOException, JAXBException, CatalogTransformerException {
    GetRecordsType query = new GetRecordsType();
    query.setResultType(ResultType.RESULTS);
    query.setMaxRecords(BigInteger.valueOf(6));
    query.setStartPosition(BigInteger.valueOf(0));
    SourceResponse sourceResponse = createSourceResponse(query, 6);
    Map<String, Serializable> args = new HashMap<>();
    args.put(CswConstants.RESULT_TYPE_PARAMETER, ResultType.RESULTS);
    args.put(CswConstants.GET_RECORDS, query);
    PrintWriter printWriter = getSimplePrintWriter();
    MetacardTransformer mockMetacardTransformer = mock(MetacardTransformer.class);
    final AtomicLong atomicLong = new AtomicLong(0);
    when(mockMetacardTransformer.transform(any(Metacard.class), anyMap())).then(invocationOnMock -> {
        if (atomicLong.incrementAndGet() == 2) {
            throw new CatalogTransformerException("");
        }
        Metacard metacard = (Metacard) invocationOnMock.getArguments()[0];
        BinaryContentImpl bci = new BinaryContentImpl(IOUtils.toInputStream(metacard.getId() + ","), new MimeType("application/xml"));
        return bci;
    });
    when(mockPrintWriterProvider.build((Class<Metacard>) notNull())).thenReturn(printWriter);
    when(mockTransformerManager.getTransformerBySchema(anyString())).thenReturn(mockMetacardTransformer);
    CswQueryResponseTransformer cswQueryResponseTransformer = new CswQueryResponseTransformer(mockTransformerManager, mockPrintWriterProvider);
    cswQueryResponseTransformer.init();
    BinaryContent content = cswQueryResponseTransformer.transform(sourceResponse, args);
    cswQueryResponseTransformer.destroy();
    String xml = new String(content.getByteArray());
    assertThat(xml, containsString(CswQueryResponseTransformer.NUMBER_OF_RECORDS_MATCHED_ATTRIBUTE + " 6"));
    assertThat(xml, containsString(CswQueryResponseTransformer.NUMBER_OF_RECORDS_RETURNED_ATTRIBUTE + " 5"));
    assertThat(xml, containsString(CswQueryResponseTransformer.NEXT_RECORD_ATTRIBUTE + " 0"));
}
Also used : Serializable(java.io.Serializable) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) SourceResponse(ddf.catalog.operation.SourceResponse) HashMap(java.util.HashMap) GetRecordsType(net.opengis.cat.csw.v_2_0_2.GetRecordsType) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.anyString(org.mockito.Matchers.anyString) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) BinaryContent(ddf.catalog.data.BinaryContent) MimeType(javax.activation.MimeType) AtomicLong(java.util.concurrent.atomic.AtomicLong) Metacard(ddf.catalog.data.Metacard) PrintWriter(ddf.catalog.transformer.api.PrintWriter) Test(org.junit.Test)

Example 37 with MimeType

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

the class AbstractXsltTransformer method init.

/**
     * Sets the templates and mimeType used to perform a transform. This method can also be used in
     * a non-OSGi environment to setup the transformer. <b>NOTE:</b> When using in a non-OSGi
     * environment, some transformers may not work.
     *
     * @param mimeHeaderName
     *            String value of the mimeType to be returned.
     * @param xslFilePath
     *            Full, absolute path of the xsl file.
     */
public void init(String mimeString, InputStream xslStream) {
    TransformerFactory tf = TransformerFactory.newInstance(net.sf.saxon.TransformerFactoryImpl.class.getName(), getClass().getClassLoader());
    Source xsltSource;
    xsltSource = new StreamSource(xslStream);
    try {
        templates = tf.newTemplates(xsltSource);
    } catch (TransformerConfigurationException tce) {
        throw new RuntimeException("Could not create new templates for XsltTransformer ( " + xslStream + ") : " + tce.getException(), tce);
    }
    if (mimeString == null) {
        this.mimeType = DEFAULT_MIME_TYPE;
        mimeString = "";
    }
    try {
        this.mimeType = new MimeType(mimeString);
    } catch (MimeTypeParseException e) {
        this.mimeType = DEFAULT_MIME_TYPE;
    }
}
Also used : MimeTypeParseException(javax.activation.MimeTypeParseException) TransformerFactory(javax.xml.transform.TransformerFactory) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) StreamSource(javax.xml.transform.stream.StreamSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) MimeType(javax.activation.MimeType)

Example 38 with MimeType

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

the class ReliableResourceDownloader method setupDownload.

public ResourceResponse setupDownload(Metacard metacard, DownloadStatusInfo downloadStatusInfo) {
    Resource resource = resourceResponse.getResource();
    MimeType mimeType = resource.getMimeType();
    String resourceName = resource.getName();
    fbos = new FileBackedOutputStream(DEFAULT_FILE_BACKED_OUTPUT_STREAM_THRESHOLD);
    countingFbos = new CountingOutputStream(fbos);
    streamReadByClient = new ReliableResourceInputStream(fbos, countingFbos, downloadState, downloadIdentifier, resourceResponse);
    this.metacard = metacard;
    // Create new ResourceResponse to return that will encapsulate the
    // ReliableResourceInputStream that will be read by the client simultaneously as the product
    // is cached to disk (if caching is enabled)
    ResourceImpl newResource = new ResourceImpl(streamReadByClient, mimeType, resourceName);
    resourceResponse = new ResourceResponseImpl(resourceResponse.getRequest(), resourceResponse.getProperties(), newResource);
    // Get handle to retrieved product's InputStream
    resourceInputStream = resource.getInputStream();
    eventListener.setDownloadMap(downloadIdentifier, resourceResponse);
    downloadStatusInfo.addDownloadInfo(downloadIdentifier, this, resourceResponse);
    if (downloaderConfig.isCacheEnabled()) {
        CacheKey keyMaker = null;
        String key = null;
        try {
            keyMaker = new CacheKey(metacard, resourceResponse.getRequest());
            key = keyMaker.generateKey();
        } catch (IllegalArgumentException e) {
            LOGGER.info("Cannot create cache key for resource with metacard ID = {}", metacard.getId());
            return resourceResponse;
        }
        if (!resourceCache.isPending(key)) {
            // Fully qualified path to cache file that will be written to.
            // Example:
            // <INSTALL-DIR>/data/product-cache/<source-id>-<metacard-id>
            // <INSTALL-DIR>/data/product-cache/ddf.distribution-abc123
            filePath = FilenameUtils.concat(resourceCache.getProductCacheDirectory(), key);
            if (filePath == null) {
                LOGGER.info("Unable to create cache for cache directory {} and key {} - no caching will be done.", resourceCache.getProductCacheDirectory(), key);
                return resourceResponse;
            }
            reliableResource = new ReliableResource(key, filePath, mimeType, resourceName, metacard);
            resourceCache.addPendingCacheEntry(reliableResource);
            try {
                fos = FileUtils.openOutputStream(new File(filePath));
                doCaching = true;
                this.downloadState.setCacheEnabled(true);
            } catch (IOException e) {
                LOGGER.info("Unable to open cache file {} - no caching will be done.", filePath);
            }
        } else {
            LOGGER.debug("Cache key {} is already pending caching", key);
        }
    }
    return resourceResponse;
}
Also used : ReliableResource(ddf.catalog.resource.data.ReliableResource) Resource(ddf.catalog.resource.Resource) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) IOException(java.io.IOException) MimeType(javax.activation.MimeType) ReliableResource(ddf.catalog.resource.data.ReliableResource) CountingOutputStream(com.google.common.io.CountingOutputStream) ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) FileBackedOutputStream(com.google.common.io.FileBackedOutputStream) File(java.io.File) CacheKey(ddf.catalog.cache.impl.CacheKey)

Example 39 with MimeType

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

the class TestXmlResponseQueueTransformer method getMimeType.

private MimeType getMimeType() throws MimeTypeParseException {
    MimeType mimeType = new MimeType();
    mimeType.setPrimaryType("text");
    mimeType.setSubType("xml");
    return mimeType;
}
Also used : MimeType(javax.activation.MimeType)

Example 40 with MimeType

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

the class InputTransformerProducer method transform.

protected Object transform(Message in, Object obj, String mimeType, String transformerId, MimeTypeToTransformerMapper mapper) throws MimeTypeParseException, IOException, CatalogTransformerException {
    // Look up the InputTransformer for the request's mime type.
    // If a transformer is found, then transform the request's payload into
    // a Metacard.
    // Otherwise, throw an exception.
    MimeType derivedMimeType = new MimeType(mimeType);
    if (transformerId != null) {
        derivedMimeType = new MimeType(mimeType + ";" + MimeTypeToTransformerMapper.ID_KEY + "=" + transformerId);
    }
    InputStream message = null;
    Metacard metacard = null;
    try {
        message = in.getBody(InputStream.class);
        if (null != message) {
            metacard = generateMetacard(derivedMimeType, mapper, message);
        } else {
            throw new CatalogTransformerException("Message body was null; unable to generate Metacard!");
        }
    } catch (MetacardCreationException e) {
        throw new CatalogTransformerException("Did not find an InputTransformer for MIME Type [" + mimeType + "] and " + MimeTypeToTransformerMapper.ID_KEY + " [" + transformerId + "]", e);
    } finally {
        if (null != message) {
            IOUtils.closeQuietly(message);
        }
    }
    return metacard;
}
Also used : Metacard(ddf.catalog.data.Metacard) MetacardCreationException(ddf.catalog.data.MetacardCreationException) InputStream(java.io.InputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) MimeType(javax.activation.MimeType)

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