Search in sources :

Example 1 with ResourceResponseImpl

use of ddf.catalog.operation.impl.ResourceResponseImpl in project ddf by codice.

the class ContentResourceReader method retrieveResource.

@Override
public ResourceResponse retrieveResource(URI resourceUri, Map<String, Serializable> arguments) throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
    LOGGER.trace("ENTERING: retrieveResource");
    ResourceResponse response = null;
    if (resourceUri == null) {
        throw new ResourceNotFoundException("Unable to find resource - resource URI was null");
    }
    if (resourceUri.getScheme().equals(ContentItem.CONTENT_SCHEME)) {
        LOGGER.debug("Resource URI is content scheme");
        String contentId = resourceUri.getSchemeSpecificPart();
        if (contentId != null && !contentId.isEmpty()) {
            if (arguments != null && arguments.get(ContentItem.QUALIFIER) instanceof String && StringUtils.isNotBlank((String) arguments.get(ContentItem.QUALIFIER))) {
                try {
                    resourceUri = new URI(resourceUri.getScheme(), resourceUri.getSchemeSpecificPart(), (String) arguments.get(ContentItem.QUALIFIER));
                } catch (URISyntaxException e) {
                    throw new ResourceNotFoundException("Unable to create with qualifier", e);
                }
            }
            ReadStorageRequest readRequest = new ReadStorageRequestImpl(resourceUri, arguments);
            try {
                ReadStorageResponse readResponse = storage.read(readRequest);
                ContentItem contentItem = readResponse.getContentItem();
                String fileName = contentItem.getFilename();
                LOGGER.debug("resource name: {}", fileName);
                InputStream is = contentItem.getInputStream();
                response = new ResourceResponseImpl(new ResourceImpl(new BufferedInputStream(is), contentItem.getMimeType(), fileName));
            } catch (StorageException e) {
                throw new ResourceNotFoundException(e);
            }
        }
    }
    LOGGER.trace("EXITING: retrieveResource");
    return response;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) ReadStorageResponse(ddf.catalog.content.operation.ReadStorageResponse) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) URI(java.net.URI) ReadStorageRequest(ddf.catalog.content.operation.ReadStorageRequest) ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) ResourceResponse(ddf.catalog.operation.ResourceResponse) BufferedInputStream(java.io.BufferedInputStream) ReadStorageRequestImpl(ddf.catalog.content.operation.impl.ReadStorageRequestImpl) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) StorageException(ddf.catalog.content.StorageException) ContentItem(ddf.catalog.content.data.ContentItem)

Example 2 with ResourceResponseImpl

use of ddf.catalog.operation.impl.ResourceResponseImpl in project ddf by codice.

the class WfsSource method retrieveResource.

@Override
public ResourceResponse retrieveResource(URI uri, Map<String, Serializable> arguments) throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
    StringBuilder strBuilder = new StringBuilder();
    strBuilder.append("<html><script type=\"text/javascript\">window.location.replace(\"");
    strBuilder.append(uri);
    strBuilder.append("\");</script></html>");
    Resource resource = new ResourceImpl(IOUtils.toInputStream(strBuilder.toString()), MediaType.TEXT_HTML, getId() + " Resource");
    return new ResourceResponseImpl(resource);
}
Also used : ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) Resource(ddf.catalog.resource.Resource) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl)

Example 3 with ResourceResponseImpl

use of ddf.catalog.operation.impl.ResourceResponseImpl in project ddf by codice.

the class ReliableResourceDownloadManager method download.

/**
     * @param resourceRequest the original @ResourceRequest to retrieve the resource
     * @param metacard        the @Metacard associated with the resource being downloaded
     * @param retriever       the @ResourceRetriever to be used to get the resource
     * @return the modified @ResourceResponse with the @ReliableResourceInputStream that the client
     * should read from
     * @throws DownloadException
     */
public ResourceResponse download(ResourceRequest resourceRequest, Metacard metacard, ResourceRetriever retriever) throws DownloadException {
    ResourceResponse resourceResponse = null;
    String downloadIdentifier = UUID.randomUUID().toString();
    if (metacard == null) {
        throw new DownloadException("Cannot download resource if metacard is null");
    } else if (StringUtils.isBlank(metacard.getId())) {
        throw new DownloadException("Metacard must have unique id.");
    } else if (retriever == null) {
        throw new DownloadException("Cannot download resource if retriever is null");
    } else if (resourceRequest == null) {
        throw new DownloadException("Cannot download resource if request is null");
    }
    if (downloaderConfig.isCacheEnabled()) {
        Resource cachedResource = downloaderConfig.getResourceCache().getValid(new CacheKey(metacard, resourceRequest).generateKey(), metacard);
        if (cachedResource != null) {
            resourceResponse = new ResourceResponseImpl(resourceRequest, resourceRequest.getProperties(), cachedResource);
            LOGGER.debug("Successfully retrieved product from cache for metacard ID = {}", metacard.getId());
        } else {
            LOGGER.debug("Unable to get resource from cache. Have to retrieve it from source");
        }
    }
    if (resourceResponse == null) {
        try {
            resourceResponse = retriever.retrieveResource();
        } catch (ResourceNotFoundException | ResourceNotSupportedException | IOException e) {
            throw new DownloadException("Cannot download resource", e);
        }
        resourceResponse.getProperties().put(Metacard.ID, metacard.getId());
        // Sources do not create ResourceResponses with the original ResourceRequest, hence
        // it is added here because it will be needed for caching
        resourceResponse = new ResourceResponseImpl(resourceRequest, resourceResponse.getProperties(), resourceResponse.getResource());
        resourceResponse = startDownload(downloadIdentifier, resourceResponse, retriever, metacard);
    }
    return resourceResponse;
}
Also used : ResourceResponse(ddf.catalog.operation.ResourceResponse) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) Resource(ddf.catalog.resource.Resource) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) IOException(java.io.IOException) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) CacheKey(ddf.catalog.cache.impl.CacheKey)

Example 4 with ResourceResponseImpl

use of ddf.catalog.operation.impl.ResourceResponseImpl in project ddf by codice.

the class TestOpenSearchSource method givenSource.

private OpenSearchSource givenSource(Answer<BinaryContent> answer) throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
    WebClient client = mock(WebClient.class);
    ResourceReader mockReader = mock(ResourceReader.class);
    Response clientResponse = mock(Response.class);
    when(clientResponse.getEntity()).thenReturn(getBinaryData());
    when(clientResponse.getHeaderString(eq(OpenSearchSource.HEADER_ACCEPT_RANGES))).thenReturn(OpenSearchSource.BYTES);
    when(client.get()).thenReturn(clientResponse);
    SecureCxfClientFactory factory = getMockFactory(client);
    when(mockReader.retrieveResource(any(URI.class), any(Map.class))).thenReturn(new ResourceResponseImpl(new ResourceImpl(getBinaryData(), "")));
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
    headers.put(HttpHeaders.CONTENT_TYPE, Arrays.<Object>asList("application/octet-stream"));
    when(clientResponse.getHeaders()).thenReturn(headers);
    OverriddenOpenSearchSource source = new OverriddenOpenSearchSource(FILTER_ADAPTER, encryptionService);
    source.setEndpointUrl("http://localhost:8181/services/catalog/query");
    source.setParameters(DEFAULT_PARAMETERS);
    source.init();
    source.setLocalQueryOnly(true);
    source.setInputTransformer(getMockInputTransformer());
    source.factory = factory;
    source.setResourceReader(mockReader);
    return source;
}
Also used : ResourceReader(ddf.catalog.resource.ResourceReader) SecureCxfClientFactory(org.codice.ddf.cxf.SecureCxfClientFactory) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) Matchers.containsString(org.hamcrest.Matchers.containsString) WebClient(org.apache.cxf.jaxrs.client.WebClient) URI(java.net.URI) Response(javax.ws.rs.core.Response) ResourceResponse(ddf.catalog.operation.ResourceResponse) SourceResponse(ddf.catalog.operation.SourceResponse) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 5 with ResourceResponseImpl

use of ddf.catalog.operation.impl.ResourceResponseImpl in project ddf by codice.

the class URLResourceReader method retrieveHttpProduct.

private ResourceResponse retrieveHttpProduct(URI resourceURI, String productName, String bytesToSkip, Map<String, Serializable> properties) throws ResourceNotFoundException {
    try {
        LOGGER.debug("Opening connection to: {}", resourceURI.toString());
        WebClient client = getWebClient(resourceURI.toString(), properties);
        Object subjectObj = properties.get(SecurityConstants.SECURITY_SUBJECT);
        if (subjectObj != null) {
            Subject subject = (Subject) subjectObj;
            LOGGER.debug("Setting Subject on webclient: {}", subject);
            RestSecurity.setSubjectOnClient(subject, client);
        }
        Response response = client.get();
        MultivaluedMap<String, Object> headers = response.getHeaders();
        List<Object> cdHeaders = headers.get(HttpHeaders.CONTENT_DISPOSITION);
        if (cdHeaders != null && !cdHeaders.isEmpty()) {
            String contentHeader = (String) cdHeaders.get(0);
            productName = StringUtils.defaultIfBlank(handleContentDispositionHeader(contentHeader), productName);
        }
        String mimeType = getMimeType(resourceURI, productName);
        Response clientResponse = client.get();
        InputStream is = null;
        Object entityObj = clientResponse.getEntity();
        if (entityObj instanceof InputStream) {
            is = (InputStream) entityObj;
            if (Response.Status.OK.getStatusCode() != clientResponse.getStatus() && Response.Status.PARTIAL_CONTENT.getStatusCode() != clientResponse.getStatus()) {
                String error = null;
                try {
                    if (is != null) {
                        error = IOUtils.toString(is);
                    }
                } catch (IOException ioe) {
                    LOGGER.debug("Could not convert error message to a string for output.", ioe);
                }
                String errorMsg = "Received error code while retrieving resource (status " + clientResponse.getStatus() + "): " + error;
                throw new ResourceNotFoundException(errorMsg);
            }
        } else {
            throw new ResourceNotFoundException("Received null response while retrieving resource.");
        }
        long responseBytesSkipped = 0L;
        if (headers.getFirst(HttpHeaders.CONTENT_RANGE) != null) {
            String contentRangeHeader = String.valueOf(headers.getFirst(HttpHeaders.CONTENT_RANGE));
            responseBytesSkipped = Long.parseLong(StringUtils.substringBetween(contentRangeHeader.toLowerCase(), "bytes ", "-"));
        }
        alignStream(is, Long.parseLong(bytesToSkip), responseBytesSkipped);
        return new ResourceResponseImpl(new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName)));
    } catch (MimeTypeResolutionException | IOException | WebApplicationException e) {
        LOGGER.info("Error retrieving resource", e);
        throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) WebClient(org.apache.cxf.jaxrs.client.WebClient) Subject(ddf.security.Subject) ResourceResponse(ddf.catalog.operation.ResourceResponse) Response(javax.ws.rs.core.Response) MimeTypeResolutionException(ddf.mime.MimeTypeResolutionException) BufferedInputStream(java.io.BufferedInputStream) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException)

Aggregations

ResourceResponseImpl (ddf.catalog.operation.impl.ResourceResponseImpl)14 Resource (ddf.catalog.resource.Resource)8 ResourceImpl (ddf.catalog.resource.impl.ResourceImpl)7 ResourceResponse (ddf.catalog.operation.ResourceResponse)6 ResourceNotFoundException (ddf.catalog.resource.ResourceNotFoundException)5 IOException (java.io.IOException)5 BufferedInputStream (java.io.BufferedInputStream)4 InputStream (java.io.InputStream)4 Serializable (java.io.Serializable)3 HashMap (java.util.HashMap)3 CacheKey (ddf.catalog.cache.impl.CacheKey)2 Metacard (ddf.catalog.data.Metacard)2 MimeTypeResolutionException (ddf.mime.MimeTypeResolutionException)2 Subject (ddf.security.Subject)2 File (java.io.File)2 URI (java.net.URI)2 MimeType (javax.activation.MimeType)2 Response (javax.ws.rs.core.Response)2 WebClient (org.apache.cxf.jaxrs.client.WebClient)2 CountingOutputStream (com.google.common.io.CountingOutputStream)1