Search in sources :

Example 51 with MimeType

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

the class TestResourceMetacardTransformer method testFrameworkThrowsResourceNotSupportedException.

@Test
public void testFrameworkThrowsResourceNotSupportedException() throws Exception {
    String filePath = ABSOLUTE_PATH + TEST_PATH + JPEG_FILE_NAME_1;
    URI uri = getUri(filePath);
    Metacard metacard = getMockMetacard(uri);
    thrown.expect(CatalogTransformerException.class);
    thrown.expectMessage("Unable to retrieve resource.");
    thrown.expectMessage("Metacard id: " + TEST_ID);
    thrown.expectMessage("Uri: " + uri);
    thrown.expectMessage("Source: " + TEST_SITE);
    boolean expectSuccess = false;
    MimeType mimeType = getMimeType(JPEG_MIME_TYPE);
    CatalogFramework framework = getFrameworkException(new ResourceNotSupportedException("Test Resource Not Supported Exception"));
    testGetResource(metacard, filePath, mimeType, framework, expectSuccess);
}
Also used : Metacard(ddf.catalog.data.Metacard) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) CatalogFramework(ddf.catalog.CatalogFramework) URI(java.net.URI) MimeType(javax.activation.MimeType) Test(org.junit.Test)

Example 52 with MimeType

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

the class ReliableResourceDownloadManagerTest method getMockResourceRetrieverWithRetryCapability.

private ResourceRetriever getMockResourceRetrieverWithRetryCapability(final RetryType retryType, final boolean readSlow) throws Exception {
    // Mocking to support re-retrieval of product when error encountered
    // during caching.
    ResourceRetriever retriever = mock(ResourceRetriever.class);
    when(retriever.retrieveResource()).thenAnswer(new Answer<Object>() {

        int invocationCount = 0;

        public Object answer(InvocationOnMock invocation) throws ResourceNotFoundException {
            // Create new InputStream for retrieving the same product. This
            // simulates re-retrieving the product from the remote source.
            invocationCount++;
            if (readSlow) {
                mis = new MockInputStream(productInputFilename, true);
                mis.setReadDelay(MONITOR_PERIOD - 2, TimeUnit.MILLISECONDS);
            } else {
                mis = new MockInputStream(productInputFilename);
            }
            if (retryType == RetryType.INPUT_STREAM_IO_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(5);
                } else {
                    mis.setInvocationCountToThrowIOException(-1);
                }
            } else if (retryType == RetryType.TIMEOUT_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToTimeout(3);
                    mis.setReadDelay(MONITOR_PERIOD * 2, TimeUnit.SECONDS);
                } else {
                    mis.setInvocationCountToTimeout(-1);
                    mis.setReadDelay(0, TimeUnit.SECONDS);
                }
            } else if (retryType == RetryType.NETWORK_CONNECTION_UP_AND_DOWN) {
                mis.setInvocationCountToThrowIOException(2);
            } else if (retryType == RetryType.NETWORK_CONNECTION_DROPPED) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(2);
                } else {
                    throw new ResourceNotFoundException();
                }
            }
            // Reset the mock Resource so that it can be reconfigured to return
            // the new InputStream
            reset(resource);
            when(resource.getInputStream()).thenReturn(mis);
            when(resource.getName()).thenReturn("test-resource");
            try {
                when(resource.getMimeType()).thenReturn(new MimeType("text/plain"));
            } catch (MimeTypeParseException e) {
            }
            // Reset the mock ResourceResponse so that it can be reconfigured to return
            // the new Resource
            reset(resourceResponse);
            when(resourceResponse.getRequest()).thenReturn(resourceRequest);
            when(resourceResponse.getResource()).thenReturn(resource);
            when(resourceResponse.getProperties()).thenReturn(new HashMap<String, Serializable>());
            return resourceResponse;
        }
    });
    ArgumentCaptor<Long> bytesReadArg = ArgumentCaptor.forClass(Long.class);
    // Mocking to support re-retrieval of product when error encountered
    // during caching. This resource retriever supports skipping.
    when(retriever.retrieveResource(anyLong())).thenAnswer(new Answer<Object>() {

        int invocationCount = 0;

        public Object answer(InvocationOnMock invocation) throws ResourceNotFoundException, IOException {
            // Create new InputStream for retrieving the same product. This
            // simulates re-retrieving the product from the remote source.
            invocationCount++;
            if (readSlow) {
                mis = new MockInputStream(productInputFilename, true);
                mis.setReadDelay(MONITOR_PERIOD - 2, TimeUnit.MILLISECONDS);
            } else {
                mis = new MockInputStream(productInputFilename);
            }
            // Skip the number of bytes that have already been read
            Object[] args = invocation.getArguments();
            long bytesToSkip = (Long) args[0];
            mis.skip(bytesToSkip);
            if (retryType == RetryType.INPUT_STREAM_IO_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(5);
                } else {
                    mis.setInvocationCountToThrowIOException(-1);
                }
            } else if (retryType == RetryType.TIMEOUT_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToTimeout(3);
                    mis.setReadDelay(MONITOR_PERIOD * 2, TimeUnit.SECONDS);
                } else {
                    mis.setInvocationCountToTimeout(-1);
                    mis.setReadDelay(0, TimeUnit.MILLISECONDS);
                }
            } else if (retryType == RetryType.NETWORK_CONNECTION_UP_AND_DOWN) {
                mis.setInvocationCountToThrowIOException(2);
            } else if (retryType == RetryType.NETWORK_CONNECTION_DROPPED) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(2);
                } else {
                    throw new ResourceNotFoundException();
                }
            }
            // Reset the mock Resource so that it can be reconfigured to return
            // the new InputStream
            reset(resource);
            when(resource.getInputStream()).thenReturn(mis);
            when(resource.getName()).thenReturn("test-resource");
            try {
                when(resource.getMimeType()).thenReturn(new MimeType("text/plain"));
            } catch (MimeTypeParseException e) {
            }
            // Reset the mock ResourceResponse so that it can be reconfigured to return
            // the new Resource
            reset(resourceResponse);
            when(resourceResponse.getRequest()).thenReturn(resourceRequest);
            when(resourceResponse.getResource()).thenReturn(resource);
            Map<String, Serializable> responseProperties = new HashMap<>();
            responseProperties.put("BytesSkipped", true);
            when(resourceResponse.getProperties()).thenReturn(responseProperties);
            when(resourceResponse.containsPropertyName("BytesSkipped")).thenReturn(true);
            when(resourceResponse.getPropertyValue("BytesSkipped")).thenReturn(true);
            return resourceResponse;
        }
    });
    return retriever;
}
Also used : MockInputStream(ddf.catalog.cache.MockInputStream) MimeTypeParseException(javax.activation.MimeTypeParseException) HashMap(java.util.HashMap) ResourceRetriever(ddf.catalog.resourceretriever.ResourceRetriever) IOException(java.io.IOException) MimeType(javax.activation.MimeType) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyLong(org.mockito.Matchers.anyLong) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 53 with MimeType

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

the class RESTEndpoint method updateDocument.

/**
     * REST Put. Updates the specified entry with the provided document.
     *
     * @param id
     * @param message
     * @return
     */
@PUT
@Path("/{id}")
@Consumes("multipart/*")
public Response updateDocument(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest httpRequest, MultipartBody multipartBody, @QueryParam("transform") String transformerParam, InputStream message) {
    LOGGER.trace("PUT");
    Response response;
    try {
        if (id != null && message != null) {
            MimeType mimeType = getMimeType(headers);
            CreateInfo createInfo = null;
            if (multipartBody != null) {
                List<Attachment> contentParts = multipartBody.getAllAttachments();
                if (contentParts != null && contentParts.size() > 0) {
                    createInfo = parseAttachments(contentParts, transformerParam);
                } else {
                    LOGGER.debug("No file contents attachment found");
                }
            }
            if (createInfo == null) {
                UpdateRequest updateRequest = new UpdateRequestImpl(id, generateMetacard(mimeType, id, message, transformerParam));
                catalogFramework.update(updateRequest);
            } else {
                UpdateStorageRequest streamUpdateRequest = new UpdateStorageRequestImpl(Collections.singletonList(new IncomingContentItem(id, createInfo.getStream(), createInfo.getContentType(), createInfo.getFilename(), 0, createInfo.getMetacard())), null);
                catalogFramework.update(streamUpdateRequest);
            }
            LOGGER.debug("Metacard {} updated.", id);
            response = Response.ok().build();
        } else {
            String errorResponseString = "Both ID and content are needed to perform UPDATE.";
            LOGGER.info(errorResponseString);
            throw new ServerErrorException(errorResponseString, Status.BAD_REQUEST);
        }
    } catch (SourceUnavailableException e) {
        String exceptionMessage = "Cannot update catalog entry: Source is unavailable: ";
        LOGGER.info(exceptionMessage, e);
        throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
    } catch (InternalIngestException e) {
        String exceptionMessage = "Error cataloging updated metadata: ";
        LOGGER.info(exceptionMessage, e);
        throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
    } catch (MetacardCreationException | IngestException e) {
        String exceptionMessage = "Error cataloging updated metadata: ";
        LOGGER.info(exceptionMessage, e);
        throw new ServerErrorException(exceptionMessage, Status.BAD_REQUEST);
    }
    return response;
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) MetacardCreationException(ddf.catalog.data.MetacardCreationException) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) InternalIngestException(ddf.catalog.source.InternalIngestException) UpdateRequest(ddf.catalog.operation.UpdateRequest) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) 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) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) IngestException(ddf.catalog.source.IngestException) InternalIngestException(ddf.catalog.source.InternalIngestException) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 54 with MimeType

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

the class TestVideoThumbnailPlugin method testCreatedItemNotVideoFile.

@Test
public void testCreatedItemNotVideoFile() throws Exception {
    mockContentItem = mock(ContentItem.class);
    doReturn(new MimeType("image/jpeg")).when(mockContentItem).getMimeType();
    Metacard mockMetacard = new MetacardImpl();
    doReturn(mockMetacard).when(mockContentItem).getMetacard();
    final CreateStorageResponse mockCreateResponse = mock(CreateStorageResponse.class);
    doReturn(Collections.singletonList(mockContentItem)).when(mockCreateResponse).getCreatedContentItems();
    final CreateStorageResponse processedCreateResponse = videoThumbnailPlugin.process(mockCreateResponse);
    assertThat(processedCreateResponse.getCreatedContentItems().get(0).getMetacard().getAttribute(Metacard.THUMBNAIL), CoreMatchers.is(nullValue()));
}
Also used : CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Metacard(ddf.catalog.data.Metacard) ContentItem(ddf.catalog.content.data.ContentItem) MimeType(javax.activation.MimeType) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Test(org.junit.Test)

Example 55 with MimeType

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

the class TestVideoThumbnailPlugin method testUpdatedItemNotVideoFile.

@Test
public void testUpdatedItemNotVideoFile() throws Exception {
    mockContentItem = mock(ContentItem.class);
    doReturn(new MimeType("application/pdf")).when(mockContentItem).getMimeType();
    Metacard mockMetacard = new MetacardImpl();
    doReturn(mockMetacard).when(mockContentItem).getMetacard();
    final UpdateStorageResponse mockUpdateResponse = mock(UpdateStorageResponse.class);
    doReturn(Collections.singletonList(mockContentItem)).when(mockUpdateResponse).getUpdatedContentItems();
    final UpdateStorageResponse processedUpdateResponse = videoThumbnailPlugin.process(mockUpdateResponse);
    assertThat(processedUpdateResponse.getUpdatedContentItems().get(0).getMetacard().getAttribute(Metacard.THUMBNAIL), CoreMatchers.is(nullValue()));
}
Also used : Metacard(ddf.catalog.data.Metacard) UpdateStorageResponse(ddf.catalog.content.operation.UpdateStorageResponse) ContentItem(ddf.catalog.content.data.ContentItem) MimeType(javax.activation.MimeType) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) 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