Search in sources :

Example 91 with MimeType

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

the class OgcUrlResourceReader method retrieveResource.

/**
 * Retrieves a {@link ddf.catalog.resource.Resource} based on a {@link URI} and provided
 * arguments. A connection is made to the {@link URI} to obtain the {@link
 * ddf.catalog.resource.Resource}'s {@link InputStream} and build a {@link ResourceResponse} from
 * that. The {@link ddf.catalog.resource.Resource}'s name gets set to the {@link URI} passed in.
 * Calls {@link URLResourceReader}, if the mime-type is "text/html" it will inject a simple script
 * to redirect to the resourceURI instead of attempting to download it.
 *
 * @param resourceURI A {@link URI} that defines what {@link Resource} to retrieve and how to do
 *     it.
 * @param properties Any additional arguments that should be passed to the {@link
 *     ddf.catalog.resource.ResourceReader}.
 * @return A {@link ResourceResponse} containing the retrieved {@link Resource}.
 * @throws ResourceNotSupportedException
 */
@Override
public ResourceResponse retrieveResource(URI resourceURI, Map<String, Serializable> properties) throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
    LOGGER.debug("Calling URLResourceReader.retrieveResource()");
    ResourceResponse response = urlResourceReader.retrieveResource(resourceURI, properties);
    Resource resource = response.getResource();
    MimeType mimeType = resource.getMimeType();
    LOGGER.debug("mimeType: {}", mimeType);
    if (mimeType != null) {
        String mimeTypeStr = mimeType.toString();
        String detectedMimeType = "";
        if (UNKNOWN_MIME_TYPES.contains(mimeTypeStr)) {
            detectedMimeType = tika.detect(resourceURI.toURL());
        }
        if (StringUtils.contains(detectedMimeType, MediaType.TEXT_HTML) || StringUtils.contains(mimeTypeStr, MediaType.TEXT_HTML)) {
            LOGGER.debug("Detected \"text\\html\". Building redirect script");
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.append("<html><script type=\"text/javascript\">window.location.replace(\"");
            strBuilder.append(resourceURI);
            strBuilder.append("\");</script></html>");
            return new ResourceResponseImpl(new ResourceImpl(new ByteArrayInputStream(strBuilder.toString().getBytes(StandardCharsets.UTF_8)), detectedMimeType, resource.getName()));
        }
    }
    return response;
}
Also used : ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) ResourceResponse(ddf.catalog.operation.ResourceResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Resource(ddf.catalog.resource.Resource) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) MimeType(javax.activation.MimeType)

Example 92 with MimeType

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

the class ResourceReaderTest method testRetrieveResourceMimeTypeTextHtml.

/**
 * Tests the case in which the Resource in the ResourceResponse returned by the URLResourceReader
 * has a text/html mime type.
 */
@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>"));
}
Also used : ResourceResponse(ddf.catalog.operation.ResourceResponse) Response(javax.ws.rs.core.Response) Serializable(java.io.Serializable) ResourceResponse(ddf.catalog.operation.ResourceResponse) URLResourceReader(ddf.catalog.resource.impl.URLResourceReader) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) URI(java.net.URI) MimeType(javax.activation.MimeType) Test(org.junit.Test)

Example 93 with MimeType

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

the class ResourceReaderTest method testRetrieveResourceOriginalUrlResourceReaderResponseReturned.

/**
 * Tests the case in which the mime type of the Resource in the ResourceResponse returned by the
 * URLResourceReader is not text/html, application/unknown or application/octet-stream. The
 * original response from the URLResourceReader is returned.
 */
@Test
public void testRetrieveResourceOriginalUrlResourceReaderResponseReturned() 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);
    ResourceResponse mockResourceResponse = getMockResourceResponse(new MimeType("image/jpeg"));
    URLResourceReader mockUrlResourceReader = getMockUrlResourceReader(uri, mockResourceResponse);
    setupMockTika(null);
    OgcUrlResourceReader resourceReader = new OgcUrlResourceReader(mockUrlResourceReader, mockTika);
    HashMap<String, Serializable> arguments = new HashMap<String, Serializable>();
    // Perform Test
    ResourceResponse resourceResponse = resourceReader.retrieveResource(uri, arguments);
    // Verify
    assertThat(resourceResponse, is(mockResourceResponse));
}
Also used : Serializable(java.io.Serializable) ResourceResponse(ddf.catalog.operation.ResourceResponse) URLResourceReader(ddf.catalog.resource.impl.URLResourceReader) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) URI(java.net.URI) MimeType(javax.activation.MimeType) Test(org.junit.Test)

Example 94 with MimeType

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

the class MimeTypeToTransformerMapperImpl method findMatches.

@Override
public <T> List<T> findMatches(Class<T> clazz, MimeType userMimeType) {
    BundleContext bundleContext = getContext();
    ServiceReference[] refs = null;
    List<T> list = new ArrayList<T>();
    if (bundleContext == null) {
        LOGGER.debug("Cannot find matches, bundle context is null.");
        return list;
    }
    if (clazz == null) {
        LOGGER.debug("Cannot find matches, service argument is null.");
        throw new IllegalArgumentException("Invalid argument supplied, null service argument");
    }
    /*
     * Extract the services using the bundle context.
     */
    try {
        refs = bundleContext.getServiceReferences(clazz.getName(), null);
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException("Invalid syntax supplied: " + userMimeType.toString());
    }
    // If no InputTransformers found, return empty list
    if (refs == null) {
        LOGGER.debug("No {} services found - return empty list", clazz.getName());
        return list;
    }
    /*
     * Sort the list of service references based in it's Comparable interface.
     */
    Arrays.sort(refs, Collections.reverseOrder());
    /*
     * If the mime type is null return the whole list of service references
     */
    if (userMimeType == null) {
        if (refs.length > 0) {
            for (ServiceReference ref : refs) {
                Object service = (bundleContext.getService(ref));
                T typedService = clazz.cast(service);
                list.add(typedService);
            }
        }
        return list;
    }
    String userIdValue = userMimeType.getParameter(MimeTypeToTransformerMapper.ID_KEY);
    List<T> strictlyMatching = new ArrayList<T>();
    for (ServiceReference ref : refs) {
        List<String> mimeTypesServicePropertyList = getServiceMimeTypesList(ref);
        String serviceId = getServiceId(ref);
        for (String mimeTypeRawEntry : mimeTypesServicePropertyList) {
            MimeType mimeTypeEntry = constructMimeType(mimeTypeRawEntry);
            if (mimeTypeEntry != null && StringUtils.equals(mimeTypeEntry.getBaseType(), userMimeType.getBaseType()) && (userIdValue == null || StringUtils.equals(userIdValue, serviceId))) {
                try {
                    Object service = bundleContext.getService(ref);
                    T typedService = clazz.cast(service);
                    strictlyMatching.add(typedService);
                    // found exact mimetype, no need to continue within
                    break;
                // the same service
                } catch (ClassCastException cce) {
                    LOGGER.debug("Caught illegal cast to transformer type. ", cce);
                }
            }
        }
    }
    return strictlyMatching;
}
Also used : ArrayList(java.util.ArrayList) MimeType(javax.activation.MimeType) ServiceReference(org.osgi.framework.ServiceReference) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleContext(org.osgi.framework.BundleContext)

Example 95 with MimeType

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

the class MimeTypeToTransformerMapperImplTest method testSingleIdMatch.

/**
 * Tests if a single id match will return only one item
 *
 * @throws MimeTypeParseException
 * @throws InvalidSyntaxException
 */
@Test
public void testSingleIdMatch() throws MimeTypeParseException, InvalidSyntaxException {
    // given
    final BundleContext context = mock(BundleContext.class);
    ServiceReference ref1 = createMockReference(1, Arrays.asList(MediaType.APPLICATION_JSON), "");
    ServiceReference ref2 = createMockReference(2, Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON), "a1");
    ServiceReference ref3 = createMockReference(3, null, null);
    ServiceReference[] refs = { ref2, ref3, ref1 };
    Object simpleTransformer1 = new Object();
    Object simpleTransformer2 = new Object();
    Object simpleTransformer3 = new Object();
    // when
    when(context.getService(ref1)).thenReturn(simpleTransformer1);
    when(context.getService(ref2)).thenReturn(simpleTransformer2);
    when(context.getService(ref3)).thenReturn(simpleTransformer3);
    when(context.getServiceReferences(isA(String.class), isNull())).thenReturn(refs);
    MimeTypeToTransformerMapper matcher = new MimeTypeToTransformerMapperImpl() {

        @Override
        protected BundleContext getContext() {
            return context;
        }
    };
    List<Object> matches = matcher.findMatches(Object.class, new MimeType(MediaType.APPLICATION_JSON + "; id=a1"));
    // then
    assertThat(matches.size(), is(1));
    assertThat(matches.get(0), is(simpleTransformer2));
}
Also used : MimeTypeToTransformerMapper(ddf.mime.MimeTypeToTransformerMapper) MimeType(javax.activation.MimeType) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Aggregations

MimeType (javax.activation.MimeType)146 Test (org.junit.Test)74 Metacard (ddf.catalog.data.Metacard)36 MimeTypeParseException (javax.activation.MimeTypeParseException)34 URI (java.net.URI)28 MimeTypeToTransformerMapper (ddf.mime.MimeTypeToTransformerMapper)25 HashMap (java.util.HashMap)25 BundleContext (org.osgi.framework.BundleContext)25 ServiceReference (org.osgi.framework.ServiceReference)25 CatalogFramework (ddf.catalog.CatalogFramework)20 Serializable (java.io.Serializable)16 ResourceResponse (ddf.catalog.operation.ResourceResponse)15 IOException (java.io.IOException)14 BinaryContentImpl (ddf.catalog.data.impl.BinaryContentImpl)11 InputStream (java.io.InputStream)10 StringWriter (java.io.StringWriter)10 MetacardCreationException (ddf.catalog.data.MetacardCreationException)9 Resource (ddf.catalog.resource.Resource)9 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)9 File (java.io.File)9