use of ddf.catalog.operation.ResourceRequest in project ddf by codice.
the class MetacardResourceSizePlugin method process.
@Override
public QueryResponse process(QueryResponse input) throws PluginExecutionException, StopProcessingException {
List<Result> results = input.getResults();
for (Result result : results) {
Metacard metacard = result.getMetacard();
if (metacard != null) {
// Can only search cache based on Metacard - no way to generate ResourceRequest with
// any properties for use in generating the CacheKey
final ResourceRequest resourceRequest = new ResourceRequestById(metacard.getId());
CacheKey cacheKey;
String key = null;
ReliableResource cachedResource = null;
try {
cacheKey = new CacheKey(metacard, resourceRequest);
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
key = cacheKey.generateKey();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
cachedResource = (ReliableResource) cache.getValid(key, metacard);
} finally {
Thread.currentThread().setContextClassLoader(tccl);
}
} catch (IllegalArgumentException e) {
LOGGER.debug("Unable to retrieve cached resource for metacard id = {}", metacard.getId());
}
if (cachedResource != null) {
long resourceSize = cachedResource.getSize();
if (resourceSize > 0 && cachedResource.hasProduct()) {
LOGGER.debug("Setting resourceSize = {} for metacard ID = {}", resourceSize, metacard.getId());
Attribute resourceSizeAttribute = new AttributeImpl(Metacard.RESOURCE_SIZE, String.valueOf(resourceSize));
metacard.setAttribute(resourceSizeAttribute);
} else {
LOGGER.debug("resourceSize <= 0 for metacard ID = {}", metacard.getId());
}
} else {
LOGGER.debug("No cached resource for cache key = {}", key);
}
}
}
return input;
}
use of ddf.catalog.operation.ResourceRequest in project ddf by codice.
the class CatalogFrameworkImplTest method testGetResourceToTestSecondResourceReaderWithSameSchemeGetsCalledIfFirstDoesNotReturnAnything.
/**
* Tests that multiple ResourceReaders with the same scheme will be invoked if the first one did
* not return a Response.
*
* @throws Exception
*/
@Test
//CACHE
@Ignore
public void testGetResourceToTestSecondResourceReaderWithSameSchemeGetsCalledIfFirstDoesNotReturnAnything() throws Exception {
String localProviderName = "ddf";
final String EXPECTED = "result from mockResourceResponse2";
final String DDF = "ddf";
// Mock a Catalog Provider
CatalogProvider provider = mock(CatalogProvider.class);
when(provider.getId()).thenReturn(localProviderName);
when(provider.isAvailable(isA(SourceMonitor.class))).thenReturn(true);
when(provider.isAvailable()).thenReturn(true);
// Mock register the provider in the container
// Mock the source poller
SourcePoller mockPoller = mock(SourcePoller.class);
when(mockPoller.getCachedSource(isA(Source.class))).thenReturn(null);
// Create two ResourceReaders. The first should not return anything
// and the second should.
ResourceReader resourceReader1 = mock(ResourceReader.class);
ResourceReader resourceReader2 = mock(ResourceReader.class);
// Set the supported Schemes so that both ResourceReaders use
// the same scheme ("DAD")
Set<String> supportedSchemes = new HashSet<String>();
supportedSchemes.add("DAD");
when(resourceReader1.getSupportedSchemes()).thenReturn(supportedSchemes);
when(resourceReader2.getSupportedSchemes()).thenReturn(supportedSchemes);
List<ResourceReader> resourceReaders = new ArrayList<ResourceReader>();
resourceReaders.add(resourceReader1);
resourceReaders.add(resourceReader2);
// Set up the requests and responses. The first ResourceReader will return null
// and the second one will retrieve a value, showing that if more than one
// ResourceReader with the same scheme are used, they will be called until a
// response is returned
ResourceRequest mockResourceRequest = mock(ResourceRequest.class);
URI myURI = new URI("DAD", "host", "/path", "fragment");
when(mockResourceRequest.getAttributeValue()).thenReturn(myURI);
when(mockResourceRequest.getAttributeName()).thenReturn(new String(ResourceRequest.GET_RESOURCE_BY_PRODUCT_URI));
Result result = mock(Result.class);
Metacard metacard = mock(Metacard.class);
when(metacard.getResourceURI()).thenReturn(myURI);
when(result.getMetacard()).thenReturn(metacard);
List<Result> results = new ArrayList<Result>();
results.add(result);
QueryResponse queryResponse = mock(QueryResponse.class);
when(queryResponse.getResults()).thenReturn(results);
List<Source> federatedSources = new ArrayList<Source>();
FederationStrategy strategy = mock(FederationStrategy.class);
when(strategy.federate(isA(federatedSources.getClass()), isA(QueryRequest.class))).thenReturn(queryResponse);
ResourceResponse mockResourceResponse1 = mock(ResourceResponse.class);
when(mockResourceResponse1.getRequest()).thenReturn(mockResourceRequest);
when(mockResourceResponse1.getResource()).thenReturn(null);
when(resourceReader1.retrieveResource(any(URI.class), anyMap())).thenReturn(null);
Resource mockResource = mock(Resource.class);
when(mockResource.getName()).thenReturn(EXPECTED);
ResourceResponse mockResourceResponse2 = mock(ResourceResponse.class);
when(mockResourceResponse2.getResource()).thenReturn(mockResource);
when(resourceReader2.retrieveResource(any(URI.class), anyMap())).thenReturn(mockResourceResponse2);
FrameworkProperties frameworkProperties = new FrameworkProperties();
frameworkProperties.setSourcePoller(mockPoller);
frameworkProperties.setResourceReaders(resourceReaders);
frameworkProperties.setFederationStrategy(strategy);
frameworkProperties.setCatalogProviders(Collections.singletonList(provider));
SourceOperations sourceOps = new SourceOperations(frameworkProperties);
QueryOperations queryOps = new QueryOperations(frameworkProperties, sourceOps, null, null);
ResourceOperations resOps = new ResourceOperations(frameworkProperties, queryOps, null);
resOps.setId(DDF);
CatalogFrameworkImpl catalogFramework = new CatalogFrameworkImpl(null, null, null, null, resOps, null, null);
sourceOps.bind(provider);
ResourceResponse response = catalogFramework.getResource(mockResourceRequest, DDF);
// Verify that the Response is as expected
org.junit.Assert.assertEquals(EXPECTED, response.getResource().getName());
// Verify that resourceReader1 was called 1 time
// This line is equivalent to verify(resourceReader1,
// times(1)).retrieveResource(any(URI.class), anyMap());
verify(resourceReader1).retrieveResource(any(URI.class), anyMap());
}
use of ddf.catalog.operation.ResourceRequest in project ddf by codice.
the class CatalogFrameworkImplTest method setup.
@Before
public void setup() throws StopProcessingException, PluginExecutionException, URISyntaxException, FederationException, IOException, CatalogTransformerException, InterruptedException {
System.setProperty("bad.files", "crossdomain.xml,clientaccesspolicy.xml,.htaccess,.htpasswd,hosts,passwd,group,resolv.conf,nfs.conf,ftpd.conf,ntp.conf,web.config,robots.txt");
System.setProperty("bad.file.extensions", ".exe,.jsp,.html,.js,.php,.phtml,.php3,.php4,.php5,.phps,.shtml,.jhtml,.pl,.py,.cgi,.msi,.com,.scr,.gadget,.application,.pif,.hta,.cpl,.msc,.jar,.kar,.bat,.cmd,.vb,.vbs,.vbe,.jse,.ws,.wsf,.wsc,.wsh,.ps1,.ps1xml,.ps2,.ps2xml,.psc1,.psc2,.msh,.msh1,.msh2,.mshxml,.msh1xml,.msh2xml,.scf,.lnk,.inf,.reg,.dll,.vxd,.cpl,.cfg,.config,.crt,.cert,.pem,.jks,.p12,.p7b,.key,.der,.csr,.jsb,.mhtml,.mht,.xhtml,.xht");
System.setProperty("bad.mime.types", "text/html,text/javascript,text/x-javascript,application/x-shellscript,text/scriptlet,application/x-msdownload,application/x-msmetafile");
// Setup
/*
* Prepare to capture the ResourceResponse argument passed into
* PostResourcePlugin.process(). We will verify that it contains a non-null ResourceRequest
* in the verification section of this test.
*/
argument = ArgumentCaptor.forClass(ResourceResponse.class);
Resource mockResource = mock(Resource.class);
mockResourceRequest = mock(ResourceRequest.class);
when(mockResourceRequest.getAttributeValue()).thenReturn(new URI("myURI"));
when(mockResourceRequest.getAttributeName()).thenReturn(new String("myName"));
mockResourceResponse = mock(ResourceResponse.class);
when(mockResourceResponse.getRequest()).thenReturn(mockResourceRequest);
when(mockResourceResponse.getResource()).thenReturn(mockResource);
mockPostResourcePlugin = mock(PostResourcePlugin.class);
/*
* We verify (see verification section of test) that PostResourcePlugin.process() receives a
* ResourceResponse with a non-null ResourceRequest. We assume that it works correctly and
* returns a ResourceResponse with a non-null ResourceRequest, so we return our
* mockResouceResponse that contains a non-null ResourceRequest.
*/
when(mockPostResourcePlugin.process(isA(ResourceResponse.class))).thenReturn(mockResourceResponse);
List<PostResourcePlugin> mockPostResourcePlugins = new ArrayList<PostResourcePlugin>();
mockPostResourcePlugins.add(mockPostResourcePlugin);
eventAdmin = new MockEventProcessor();
provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(), true, new Date());
storageProvider = new MockMemoryStorageProvider();
// Mock register the provider in the container
// Mock the source poller
SourcePoller mockPoller = mock(SourcePoller.class);
when(mockPoller.getCachedSource(isA(Source.class))).thenReturn(null);
ArrayList<PostIngestPlugin> postIngestPlugins = new ArrayList<PostIngestPlugin>();
postIngestPlugins.add(eventAdmin);
mockFederationStrategy = mock(FederationStrategy.class);
Result mockFederationResult = mock(Result.class);
when(mockFederationResult.getMetacard()).thenReturn(new MetacardImpl());
QueryRequest mockQueryRequest = mock(QueryRequest.class);
Query mockQuery = mock(Query.class);
when(mockQuery.getTimeoutMillis()).thenReturn(1L);
when(mockQueryRequest.getQuery()).thenReturn(mockQuery);
QueryResponseImpl queryResponse = new QueryResponseImpl(mockQueryRequest, Collections.singletonList(mockFederationResult), 1);
when(mockFederationStrategy.federate(anyList(), anyObject())).thenReturn(queryResponse);
federatedSources = createDefaultFederatedSourceList(true);
MimeTypeResolver mimeTypeResolver = mock(MimeTypeResolver.class);
MimeTypeToTransformerMapper mimeTypeToTransformerMapper = mock(MimeTypeToTransformerMapper.class);
InputTransformer inputTransformer = mock(InputTransformer.class);
when(inputTransformer.transform(any(InputStream.class))).thenReturn(new MetacardImpl());
when(mimeTypeToTransformerMapper.findMatches(any(Class.class), any(MimeType.class))).thenReturn(Collections.singletonList(inputTransformer));
mockRemoteDeleteOperations = mock(RemoteDeleteOperations.class);
FrameworkProperties frameworkProperties = new FrameworkProperties();
frameworkProperties.setAccessPlugins(new ArrayList<>());
frameworkProperties.setPolicyPlugins(new ArrayList<>());
frameworkProperties.setSourcePoller(mockPoller);
frameworkProperties.setCatalogProviders(Collections.singletonList((CatalogProvider) provider));
frameworkProperties.setPostResource(mockPostResourcePlugins);
frameworkProperties.setFederationStrategy(mockFederationStrategy);
frameworkProperties.setFilterBuilder(new GeotoolsFilterBuilder());
frameworkProperties.setPreIngest(new ArrayList<>());
frameworkProperties.setPostIngest(postIngestPlugins);
frameworkProperties.setPreQuery(new ArrayList<>());
frameworkProperties.setPostQuery(new ArrayList<>());
frameworkProperties.setPreResource(new ArrayList<>());
frameworkProperties.setPostResource(new ArrayList<>());
frameworkProperties.setQueryResponsePostProcessor(mock(QueryResponsePostProcessor.class));
frameworkProperties.setStorageProviders(Collections.singletonList(storageProvider));
frameworkProperties.setMimeTypeMapper(new MimeTypeMapperImpl(Collections.singletonList(mimeTypeResolver)));
frameworkProperties.setMimeTypeToTransformerMapper(mimeTypeToTransformerMapper);
frameworkProperties.setValidationQueryFactory(new ValidationQueryFactory(new GeotoolsFilterAdapterImpl(), new GeotoolsFilterBuilder()));
Map<String, FederatedSource> federatedSourceMap = new HashMap<>();
if (federatedSources != null) {
for (FederatedSource source : federatedSources) {
federatedSourceMap.put(source.getId(), source);
}
}
SourcePollerRunner runner = new SourcePollerRunner();
SourcePoller poller = new SourcePoller(runner);
for (FederatedSource source : federatedSources) {
runner.bind(source);
}
runner.bind(provider);
int wait = 0;
while (wait < 5) {
for (FederatedSource source : federatedSources) {
CachedSource cachedSource = poller.getCachedSource(source);
if (cachedSource == null || !cachedSource.isAvailable()) {
Thread.sleep(100);
wait++;
break;
}
}
CachedSource cachedProvider = poller.getCachedSource(provider);
if (cachedProvider == null || !cachedProvider.isAvailable()) {
Thread.sleep(100);
}
wait++;
}
frameworkProperties.setSourcePoller(poller);
frameworkProperties.setFederatedSources(federatedSourceMap);
defaultAttributeValueRegistry = new DefaultAttributeValueRegistryImpl();
frameworkProperties.setDefaultAttributeValueRegistry(defaultAttributeValueRegistry);
attributeInjector = spy(new AttributeInjectorImpl(new AttributeRegistryImpl()));
frameworkProperties.setAttributeInjectors(Collections.singletonList(attributeInjector));
uuidGenerator = mock(UuidGenerator.class);
when(uuidGenerator.generateUuid()).thenReturn(UUID.randomUUID().toString());
OperationsSecuritySupport opsSecurity = new OperationsSecuritySupport();
MetacardFactory metacardFactory = new MetacardFactory(mimeTypeToTransformerMapper, uuidGenerator);
OperationsMetacardSupport opsMetacard = new OperationsMetacardSupport(frameworkProperties, metacardFactory);
SourceOperations sourceOperations = new SourceOperations(frameworkProperties);
TransformOperations transformOperations = new TransformOperations(frameworkProperties);
Historian historian = new Historian();
historian.setHistoryEnabled(false);
QueryOperations queryOperations = new QueryOperations(frameworkProperties, sourceOperations, opsSecurity, opsMetacard);
OperationsStorageSupport opsStorage = new OperationsStorageSupport(sourceOperations, queryOperations);
opsStorage.setHistorian(historian);
OperationsCatalogStoreSupport opsCatStore = new OperationsCatalogStoreSupport(frameworkProperties, sourceOperations);
CreateOperations createOperations = new CreateOperations(frameworkProperties, queryOperations, sourceOperations, opsSecurity, opsMetacard, opsCatStore, opsStorage);
UpdateOperations updateOperations = new UpdateOperations(frameworkProperties, queryOperations, sourceOperations, opsSecurity, opsMetacard, opsCatStore, opsStorage);
deleteOperations = new DeleteOperations(frameworkProperties, queryOperations, sourceOperations, opsSecurity, opsMetacard);
deleteOperations.setOpsCatStoreSupport(opsCatStore);
ResourceOperations resOps = new ResourceOperations(frameworkProperties, queryOperations, opsSecurity) {
@Override
protected ResourceInfo getResourceInfo(ResourceRequest resourceRequest, String site, boolean isEnterprise, StringBuilder federatedSite, Map<String, Serializable> requestProperties, boolean fanoutEnabled) throws ResourceNotSupportedException, ResourceNotFoundException {
URI uri = null;
Metacard metacard = new MetacardImpl();
try {
uri = new URI("myURI");
} catch (URISyntaxException e) {
}
return new ResourceInfo(metacard, uri);
}
};
updateOperations.setHistorian(historian);
deleteOperations.setHistorian(historian);
framework = new CatalogFrameworkImpl(createOperations, updateOperations, deleteOperations, queryOperations, resOps, sourceOperations, transformOperations);
// Conditionally bind objects if framework properties are setup
if (!CollectionUtils.isEmpty(frameworkProperties.getCatalogProviders())) {
sourceOperations.bind(provider);
}
sourceOperations.bind(storageProvider);
resourceFramework = new CatalogFrameworkImpl(createOperations, updateOperations, deleteOperations, queryOperations, resOps, sourceOperations, transformOperations);
// Conditionally bind objects if framework properties are setup
if (!CollectionUtils.isEmpty(frameworkProperties.getCatalogProviders())) {
sourceOperations.bind(provider);
}
sourceOperations.bind(storageProvider);
ThreadContext.bind(mock(Subject.class));
}
use of ddf.catalog.operation.ResourceRequest in project ddf by codice.
the class ResourceMetacardTransformer method transform.
@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException {
LOGGER.trace("Entering resource ResourceMetacardTransformer.transform");
if (!isValid(metacard)) {
throw new CatalogTransformerException("Could not transform metacard to a resource because the metacard is not valid.");
}
if (StringUtils.isNotEmpty(metacard.getResourceSize())) {
arguments.put(Metacard.RESOURCE_SIZE, metacard.getResourceSize());
}
String id = metacard.getId();
LOGGER.debug("executing resource request with id '{}'", id);
final ResourceRequest resourceRequest = new ResourceRequestById(id, arguments);
ResourceResponse resourceResponse = null;
String sourceName = metacard.getSourceId();
if (StringUtils.isBlank(sourceName)) {
sourceName = catalogFramework.getId();
}
String resourceUriAscii = "";
if (metacard.getResourceURI() != null) {
resourceUriAscii = metacard.getResourceURI().toASCIIString();
}
try {
resourceResponse = catalogFramework.getResource(resourceRequest, sourceName);
} catch (IOException e) {
throw new CatalogTransformerException(retrieveResourceFailureMessage(id, sourceName, resourceUriAscii, e.getMessage()), e);
} catch (ResourceNotFoundException e) {
throw new CatalogTransformerException(retrieveResourceFailureMessage(id, sourceName, resourceUriAscii, e.getMessage()), e);
} catch (ResourceNotSupportedException e) {
throw new CatalogTransformerException(retrieveResourceFailureMessage(id, sourceName, resourceUriAscii, e.getMessage()), e);
}
if (resourceResponse == null) {
throw new CatalogTransformerException(retrieveResourceFailureMessage(id, sourceName, resourceUriAscii));
}
Resource transformedContent = resourceResponse.getResource();
MimeType mimeType = transformedContent.getMimeType();
if (mimeType == null) {
try {
mimeType = new MimeType(DEFAULT_MIME_TYPE_STR);
// There is no method to set the MIME type, so in order to set it to our default
// one, we need to create a new object.
transformedContent = new ResourceImpl(transformedContent.getInputStream(), mimeType, transformedContent.getName());
} catch (MimeTypeParseException e) {
throw new CatalogTransformerException("Could not create default mime type upon null mimeType, for default mime type '" + DEFAULT_MIME_TYPE_STR + "'.", e);
}
}
LOGGER.debug("Found mime type: '{}' for product of metacard with id: '{}'.\nGetting associated resource from input stream. \n", mimeType, id);
LOGGER.trace("Exiting resource transform for metacard id: '{}'", id);
return transformedContent;
}
use of ddf.catalog.operation.ResourceRequest in project ddf by codice.
the class TestResourceUsagePlugin method getMockResourceRequest.
private ResourceRequest getMockResourceRequest(String resourceSize, String expectedUsername) {
setSubject(expectedUsername);
ResourceRequest resourceRequest = mock(ResourceRequest.class);
Map<String, Serializable> requestProperties = new HashMap<>();
requestProperties.put(SecurityConstants.SECURITY_SUBJECT, subject);
requestProperties.put(Metacard.RESOURCE_SIZE, resourceSize);
when(resourceRequest.getPropertyNames()).thenReturn(requestProperties.keySet());
when(resourceRequest.getPropertyValue(SecurityConstants.SECURITY_SUBJECT)).thenReturn(subject);
when(resourceRequest.getPropertyValue(Metacard.RESOURCE_SIZE)).thenReturn(resourceSize);
return resourceRequest;
}
Aggregations