Search in sources :

Example 31 with ResourceNotFoundException

use of ddf.catalog.resource.ResourceNotFoundException in project ddf by codice.

the class SeedCommand method executeWithSubject.

@Override
protected Object executeWithSubject() throws Exception {
    if (resourceLimit <= 0) {
        printErrorMessage("A limit of " + resourceLimit + " was supplied. The limit must be greater than 0.");
        return null;
    }
    final long start = System.currentTimeMillis();
    int resourceDownloads = 0;
    int downloadErrors = 0;
    int pageCount = 0;
    while (resourceDownloads < resourceLimit) {
        final QueryImpl query = new QueryImpl(getFilter());
        query.setPageSize(resourceLimit);
        query.setStartIndex(pageCount * resourceLimit + 1);
        ++pageCount;
        final QueryRequestImpl queryRequest;
        if (isNotEmpty(sources)) {
            queryRequest = new QueryRequestImpl(query, sources);
        } else {
            queryRequest = new QueryRequestImpl(query, true);
        }
        final QueryResponse queryResponse = catalogFramework.query(queryRequest);
        if (queryResponse.getResults().isEmpty()) {
            break;
        }
        final List<Entry<? extends ResourceRequest, String>> resourceRequests = queryResponse.getResults().stream().map(Result::getMetacard).filter(isNonCachedResource).map(metacard -> new SimpleEntry<>(new ResourceRequestById(metacard.getId()), metacard.getSourceId())).collect(toList());
        for (Entry<? extends ResourceRequest, String> requestAndSourceId : resourceRequests) {
            final ResourceRequest request = requestAndSourceId.getKey();
            try {
                ResourceResponse response = catalogFramework.getResource(request, requestAndSourceId.getValue());
                ++resourceDownloads;
                EXECUTOR.execute(new ResourceCloseHandler(response));
            } catch (IOException | ResourceNotFoundException | ResourceNotSupportedException e) {
                ++downloadErrors;
                LOGGER.debug("Could not download resource for metacard [id={}]", request.getAttributeValue(), e);
            }
            printProgressAndFlush(start, resourceLimit, resourceDownloads);
            if (resourceDownloads == resourceLimit) {
                break;
            }
        }
    }
    printProgressAndFlush(start, resourceDownloads, resourceDownloads);
    console.println();
    if (downloadErrors > 0) {
        printErrorMessage(downloadErrors + " resource download(s) had errors. Check the logs for details.");
    }
    printSuccessMessage("Done seeding. " + resourceDownloads + " resource download(s) started.");
    return null;
}
Also used : ResourceResponse(ddf.catalog.operation.ResourceResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) LoggerFactory(org.slf4j.LoggerFactory) Command(org.apache.karaf.shell.api.action.Command) Metacard(ddf.catalog.data.Metacard) ResourceRequest(ddf.catalog.operation.ResourceRequest) SimpleEntry(java.util.AbstractMap.SimpleEntry) Result(ddf.catalog.data.Result) CollectionUtils.isNotEmpty(org.apache.commons.collections.CollectionUtils.isNotEmpty) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) StandardThreadFactoryBuilder(org.codice.ddf.platform.util.StandardThreadFactoryBuilder) ResourceRequestById(ddf.catalog.operation.impl.ResourceRequestById) IOException(java.io.IOException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) TimeUnit(java.util.concurrent.TimeUnit) QueryResponse(ddf.catalog.operation.QueryResponse) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Attribute(ddf.catalog.data.Attribute) Entry(java.util.Map.Entry) Service(org.apache.karaf.shell.api.action.lifecycle.Service) Option(org.apache.karaf.shell.api.action.Option) InputStream(java.io.InputStream) SimpleEntry(java.util.AbstractMap.SimpleEntry) IOException(java.io.IOException) QueryImpl(ddf.catalog.operation.impl.QueryImpl) SimpleEntry(java.util.AbstractMap.SimpleEntry) Entry(java.util.Map.Entry) ResourceResponse(ddf.catalog.operation.ResourceResponse) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) QueryResponse(ddf.catalog.operation.QueryResponse) ResourceRequestById(ddf.catalog.operation.impl.ResourceRequestById) ResourceRequest(ddf.catalog.operation.ResourceRequest) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException)

Example 32 with ResourceNotFoundException

use of ddf.catalog.resource.ResourceNotFoundException in project ddf by codice.

the class DumpCommand method getResource.

private Resource getResource(Metacard metacard) {
    Resource resource = null;
    try {
        ResourceRequest resourceRequest = new ResourceRequestById(metacard.getId());
        ResourceResponse resourceResponse = catalogFramework.getLocalResource(resourceRequest);
        resource = resourceResponse.getResource();
    } catch (IOException | ResourceNotFoundException | ResourceNotSupportedException e) {
        LOGGER.debug("Unable to retrieve content from metacard : {}", metacard.getId(), e);
    }
    return resource;
}
Also used : ResourceResponse(ddf.catalog.operation.ResourceResponse) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) Resource(ddf.catalog.resource.Resource) ResourceRequestById(ddf.catalog.operation.impl.ResourceRequestById) ResourceRequest(ddf.catalog.operation.ResourceRequest) IOException(java.io.IOException) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException)

Example 33 with ResourceNotFoundException

use of ddf.catalog.resource.ResourceNotFoundException 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) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 34 with ResourceNotFoundException

use of ddf.catalog.resource.ResourceNotFoundException in project ddf by codice.

the class URLResourceReader method retrieveFileProduct.

private ResourceResponse retrieveFileProduct(URI resourceURI, String productName, String bytesToSkip) throws ResourceNotFoundException {
    URLConnection connection;
    try {
        LOGGER.debug("Opening connection to: {}", resourceURI);
        connection = resourceURI.toURL().openConnection();
        final String originalFileName = productName;
        productName = AccessController.doPrivileged((PrivilegedAction<String>) () -> StringUtils.defaultIfBlank(handleContentDispositionHeader(connection.getHeaderField(HttpHeaders.CONTENT_DISPOSITION)), originalFileName));
        String mimeType = getMimeType(resourceURI, productName);
        InputStream is = connection.getInputStream();
        skipBytes(is, bytesToSkip);
        return new ResourceResponseImpl(new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName)));
    } catch (MimeTypeResolutionException | IOException e) {
        LOGGER.info("Error retrieving resource", e);
        throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e);
    }
}
Also used : MimeTypeResolutionException(ddf.mime.MimeTypeResolutionException) PrivilegedAction(java.security.PrivilegedAction) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) IOException(java.io.IOException) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) URLConnection(java.net.URLConnection)

Example 35 with ResourceNotFoundException

use of ddf.catalog.resource.ResourceNotFoundException in project ddf by codice.

the class URLResourceReaderTest method testURLResourceIOException.

@Test
public void testURLResourceIOException() throws Exception {
    URLResourceReader resourceReader = new URLResourceReader(mimeTypeMapper, clientBuilderFactory);
    String filePath = "JUMANJI!!!!";
    HashMap<String, Serializable> arguments = new HashMap<String, Serializable>();
    try {
        LOGGER.info("Getting resource: {}", filePath);
        URI uri = new URI(FILE_SCHEME_PLUS_SEP + filePath);
        resourceReader.retrieveResource(uri, arguments);
    } catch (IOException e) {
        LOGGER.info("Successfully caught IOException");
        fail();
    } catch (ResourceNotFoundException e) {
        LOGGER.info("Caught ResourceNotFoundException");
        assert (true);
    } catch (URISyntaxException e) {
        LOGGER.info("Caught unexpected URISyntaxException");
        fail();
    }
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) URI(java.net.URI) Test(org.junit.Test)

Aggregations

ResourceNotFoundException (ddf.catalog.resource.ResourceNotFoundException)41 IOException (java.io.IOException)25 ResourceResponse (ddf.catalog.operation.ResourceResponse)17 URI (java.net.URI)16 ResourceNotSupportedException (ddf.catalog.resource.ResourceNotSupportedException)14 Serializable (java.io.Serializable)14 Metacard (ddf.catalog.data.Metacard)13 Test (org.junit.Test)12 HashMap (java.util.HashMap)11 URISyntaxException (java.net.URISyntaxException)10 Result (ddf.catalog.data.Result)8 ResourceRequest (ddf.catalog.operation.ResourceRequest)8 QueryRequestImpl (ddf.catalog.operation.impl.QueryRequestImpl)8 ResourceRequestById (ddf.catalog.operation.impl.ResourceRequestById)7 Resource (ddf.catalog.resource.Resource)7 QueryRequest (ddf.catalog.operation.QueryRequest)6 QueryResponse (ddf.catalog.operation.QueryResponse)6 ResourceResponseImpl (ddf.catalog.operation.impl.ResourceResponseImpl)6 CatalogFramework (ddf.catalog.CatalogFramework)5 FederationException (ddf.catalog.federation.FederationException)5