Search in sources :

Example 31 with CreateResponse

use of ddf.catalog.operation.CreateResponse in project ddf by codice.

the class DuplicateCommands method ingestMetacards.

protected List<Metacard> ingestMetacards(CatalogFacade provider, List<Metacard> metacards) {
    if (metacards.isEmpty()) {
        return Collections.emptyList();
    }
    List<Metacard> createdMetacards = new ArrayList<>();
    LOGGER.debug("Preparing to ingest {} records", metacards.size());
    CreateRequest createRequest = new CreateRequestImpl(metacards);
    CreateResponse createResponse;
    try {
        createResponse = provider.create(createRequest);
        createdMetacards = createResponse.getCreatedMetacards();
    } catch (IngestException e) {
        printErrorMessage(String.format("Received error while ingesting: %s%n", e.getMessage()));
        LOGGER.debug("Error during ingest. Attempting to ingest batch individually.");
        return ingestSingly(provider, metacards);
    } catch (SourceUnavailableException e) {
        printErrorMessage(String.format("Received error while ingesting: %s%n", e.getMessage()));
        LOGGER.debug("Error during ingest:", e);
        return createdMetacards;
    } catch (Exception e) {
        printErrorMessage(String.format("Unexpected Exception received while ingesting: %s%n", e.getMessage()));
        LOGGER.debug("Unexpected Exception during ingest:", e);
        return createdMetacards;
    }
    ingestedCount.addAndGet(createdMetacards.size());
    failedCount.addAndGet(metacards.size() - createdMetacards.size());
    failedMetacards.addAll(subtract(metacards, createdMetacards));
    return createdMetacards;
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) Metacard(ddf.catalog.data.Metacard) CreateRequest(ddf.catalog.operation.CreateRequest) CreateResponse(ddf.catalog.operation.CreateResponse) ArrayList(java.util.ArrayList) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) IngestException(ddf.catalog.source.IngestException) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException)

Example 32 with CreateResponse

use of ddf.catalog.operation.CreateResponse in project ddf by codice.

the class ContentProducerDataAccessObjectTest method testCreateContentItem.

@Test
public void testCreateContentItem() throws Exception {
    File testFile = temporaryFolder.newFile("testCreateContentItem.txt");
    // make sample list of metacard and set of keys
    List<MetacardImpl> metacardList = ImmutableList.of(new MetacardImpl());
    String uri = testFile.toURI().toASCIIString();
    Set<String> keys = new HashSet<>(Collections.singletonList(String.valueOf(DigestUtils.sha1Hex(uri))));
    // mock out responses for create, delete, update
    CreateResponse mockCreateResponse = mock(CreateResponse.class);
    doReturn(metacardList).when(mockCreateResponse).getCreatedMetacards();
    DeleteResponse mockDeleteResponse = mock(DeleteResponse.class);
    doReturn(metacardList).when(mockDeleteResponse).getDeletedMetacards();
    UpdateResponse mockUpdateResponse = mock(UpdateResponse.class);
    doReturn(metacardList).when(mockUpdateResponse).getUpdatedMetacards();
    // setup mockFileSystemPersistenceProvider
    FileSystemPersistenceProvider mockFileSystemPersistenceProvider = mock(FileSystemPersistenceProvider.class);
    doReturn(keys).when(mockFileSystemPersistenceProvider).loadAllKeys();
    doAnswer(invocationOnMock -> keys.remove(invocationOnMock.getArguments()[0])).when(mockFileSystemPersistenceProvider).delete(anyString());
    doReturn("sample").when(mockFileSystemPersistenceProvider).loadFromPersistence(any(String.class));
    // setup mockCatalogFramework
    CatalogFramework mockCatalogFramework = mock(CatalogFramework.class);
    doReturn(mockCreateResponse).when(mockCatalogFramework).create(any(CreateStorageRequest.class));
    doReturn(mockDeleteResponse).when(mockCatalogFramework).delete(any(DeleteRequest.class));
    // setup mockSourceInfo
    SourceInfoResponse mockSourceInfoResponse = mock(SourceInfoResponse.class);
    SourceDescriptor mockSourceDescriptor = mock(SourceDescriptor.class);
    when(mockSourceDescriptor.isAvailable()).thenReturn(true);
    when(mockSourceInfoResponse.getSourceInfo()).thenReturn(Collections.singleton(mockSourceDescriptor));
    when(mockCatalogFramework.getSourceInfo(any(SourceInfoRequest.class))).thenReturn(mockSourceInfoResponse);
    // setup mockComponent
    ContentComponent mockComponent = mock(ContentComponent.class);
    doReturn(mockCatalogFramework).when(mockComponent).getCatalogFramework();
    // setup mockEndpoint
    ContentEndpoint mockEndpoint = mock(ContentEndpoint.class);
    doReturn(mockComponent).when(mockEndpoint).getComponent();
    WatchEvent.Kind<Path> kind;
    String mimeType = "txt";
    Map<String, Object> headers = new HashedMap();
    Map<String, Serializable> attributeOverrides = new HashMap<>();
    attributeOverrides.put("example", ImmutableList.of("something", "something1"));
    attributeOverrides.put("example2", ImmutableList.of("something2"));
    headers.put(Constants.ATTRIBUTE_OVERRIDES_KEY, attributeOverrides);
    headers.put(Constants.STORE_REFERENCE_KEY, uri);
    kind = StandardWatchEventKinds.ENTRY_CREATE;
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers);
    verify(mockCatalogFramework).create(any(CreateStorageRequest.class));
    kind = StandardWatchEventKinds.ENTRY_MODIFY;
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers);
    verify(mockCatalogFramework).update(any(UpdateStorageRequest.class));
    kind = StandardWatchEventKinds.ENTRY_DELETE;
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers);
    verify(mockCatalogFramework).delete(any(DeleteRequest.class));
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers);
    verify(mockCatalogFramework).delete(any(DeleteRequest.class));
}
Also used : SourceDescriptor(ddf.catalog.source.SourceDescriptor) Serializable(java.io.Serializable) HashMap(java.util.HashMap) CreateResponse(ddf.catalog.operation.CreateResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) UpdateResponse(ddf.catalog.operation.UpdateResponse) SourceInfoRequest(ddf.catalog.operation.SourceInfoRequest) CatalogFramework(ddf.catalog.CatalogFramework) WatchEvent(java.nio.file.WatchEvent) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) HashSet(java.util.HashSet) Path(java.nio.file.Path) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) DeleteResponse(ddf.catalog.operation.DeleteResponse) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) HashedMap(org.apache.commons.collections.map.HashedMap) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) DeleteRequest(ddf.catalog.operation.DeleteRequest) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest) Test(org.junit.Test)

Example 33 with CreateResponse

use of ddf.catalog.operation.CreateResponse in project ddf by codice.

the class IngestCommand method processBatch.

private boolean processBatch(CatalogFacade catalog, ArrayList<Metacard> metacards) throws SourceUnavailableException {
    CreateResponse createResponse = null;
    try {
        createResponse = createMetacards(catalog, metacards);
    } catch (IngestException e) {
        printErrorMessage("Error executing command: " + e.getMessage());
        if (INGEST_LOGGER.isWarnEnabled()) {
            INGEST_LOGGER.warn("Error ingesting metacard batch {}", buildIngestLog(metacards), e);
        }
    } catch (SourceUnavailableException e) {
        if (INGEST_LOGGER.isWarnEnabled()) {
            INGEST_LOGGER.warn("Error on process batch, local Provider not available. {}" + " metacards failed to ingest. {}", metacards.size(), buildIngestLog(metacards), e);
        }
    } finally {
        IntStream range = IntStream.range(0, metacards.size());
        range.forEach(i -> phaser.arriveAndDeregister());
        range.close();
    }
    if (createResponse != null) {
        ingestCount.getAndAdd(metacards.size());
    }
    return createResponse != null;
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) CreateResponse(ddf.catalog.operation.CreateResponse) IngestException(ddf.catalog.source.IngestException) IntStream(java.util.stream.IntStream)

Example 34 with CreateResponse

use of ddf.catalog.operation.CreateResponse in project ddf by codice.

the class MockMemoryProvider method create.

@Override
public CreateResponse create(CreateRequest request) {
    List<Metacard> oldCards = request.getMetacards();
    hasReceivedCreate = true;
    List<Metacard> returnedMetacards = new ArrayList<>(oldCards.size());
    Map<String, Serializable> properties = new HashMap<>();
    for (Metacard curCard : oldCards) {
        MetacardImpl card = new MetacardImpl(curCard);
        if (card.getId() == null) {
            card.setId(UUID.randomUUID().toString());
        }
        LOGGER.debug("Storing metacard with id: {}", card.getId());
        store.put(card.getId(), card);
        properties.put(card.getId(), card);
        returnedMetacards.add(card);
    }
    CreateResponse ingestResponseImpl = new CreateResponseImpl(request, properties, returnedMetacards);
    return ingestResponseImpl;
}
Also used : Metacard(ddf.catalog.data.Metacard) Serializable(java.io.Serializable) HashMap(java.util.HashMap) CreateResponse(ddf.catalog.operation.CreateResponse) ArrayList(java.util.ArrayList) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) CreateResponseImpl(ddf.catalog.operation.impl.CreateResponseImpl)

Example 35 with CreateResponse

use of ddf.catalog.operation.CreateResponse in project ddf by codice.

the class Historian method version.

/**
 * Versions updated {@link Metacard}s and {@link ContentItem}s.
 *
 * @param streamUpdateRequest Needed to pass {@link
 *     ddf.catalog.core.versioning.MetacardVersion#SKIP_VERSIONING} flag into downstream update
 * @param updateStorageResponse Versions this response's updated items
 * @return the update response originally passed in
 * @throws UnsupportedQueryException
 * @throws SourceUnavailableException
 * @throws IngestException
 */
public UpdateStorageResponse version(UpdateStorageRequest streamUpdateRequest, UpdateStorageResponse updateStorageResponse, UpdateResponse updateResponse) throws UnsupportedQueryException, SourceUnavailableException, IngestException {
    if (doSkip(updateStorageResponse)) {
        return updateStorageResponse;
    }
    setSkipFlag(streamUpdateRequest);
    setSkipFlag(updateStorageResponse);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Versioning updated metacards and content: {}", updateStorageResponse);
    }
    List<Metacard> updatedMetacards = updateStorageResponse.getUpdatedContentItems().stream().filter(ci -> StringUtils.isBlank(ci.getQualifier())).map(ContentItem::getMetacard).filter(Objects::nonNull).filter(isNotVersionNorDeleted).collect(Collectors.toList());
    if (updatedMetacards.isEmpty()) {
        LOGGER.trace("No updated metacards applicable to versioning");
        securityLogger.audit("Skipping versioning updated metacards with ids: {}", updateStorageResponse.getUpdatedContentItems().stream().map(ContentItem::getMetacard).filter(Objects::nonNull).map(Metacard::getId).collect(TO_A_STRING));
        return updateStorageResponse;
    }
    Map<String, Metacard> originalMetacards = updateResponse.getUpdatedMetacards().stream().map(Update::getOldMetacard).collect(Collectors.toMap(Metacard::getId, Function.identity(), Historian::firstInWinsMerge));
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Found current data for the following metacards: {}", getList(originalMetacards));
    }
    Collection<ReadStorageRequest> ids = getReadStorageRequests(updatedMetacards);
    Map<String, List<ContentItem>> content = getContent(ids);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Found resources for the following metacards: {}", getList(content));
    }
    Function<String, Action> getAction = id -> content.containsKey(id) ? Action.VERSIONED_CONTENT : Action.VERSIONED;
    Map<String, Metacard> versionMetacards = getVersionMetacards(originalMetacards.values(), getAction, (Subject) updateResponse.getProperties().get(SecurityConstants.SECURITY_SUBJECT));
    CreateStorageResponse createStorageResponse = versionContentItems(content, versionMetacards);
    if (createStorageResponse == null) {
        String message = "Could not version content items for: " + getList(originalMetacards);
        securityLogger.audit(message);
        LOGGER.debug(message);
        return updateStorageResponse;
    }
    setResourceUriForContent(/*mutable*/
    versionMetacards, createStorageResponse);
    CreateResponse createResponse = storeVersionMetacards(versionMetacards);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Successfully created metacard versions under ids: {}", createResponse.getCreatedMetacards().stream().map(Metacard::getId).collect(TO_A_STRING));
    }
    return updateStorageResponse;
}
Also used : UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) LoggerFactory(org.slf4j.LoggerFactory) ReadStorageRequest(ddf.catalog.content.operation.ReadStorageRequest) StringUtils(org.apache.commons.lang3.StringUtils) SubjectOperations(ddf.security.SubjectOperations) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) DeletedMetacardImpl(ddf.catalog.core.versioning.impl.DeletedMetacardImpl) LogSanitizer(org.codice.ddf.log.sanitizer.LogSanitizer) Map(java.util.Map) Action(ddf.catalog.core.versioning.MetacardVersion.Action) Collector(java.util.stream.Collector) UpdateStorageResponse(ddf.catalog.content.operation.UpdateStorageResponse) Bundle(org.osgi.framework.Bundle) MetacardVersionImpl(ddf.catalog.core.versioning.impl.MetacardVersionImpl) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) Predicate(java.util.function.Predicate) Collection(java.util.Collection) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) MetacardType(ddf.catalog.data.MetacardType) BundleContext(org.osgi.framework.BundleContext) Objects(java.util.Objects) StorageException(ddf.catalog.content.StorageException) Operation(ddf.catalog.operation.Operation) List(java.util.List) CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Optional(java.util.Optional) UpdateResponse(ddf.catalog.operation.UpdateResponse) AccessController(java.security.AccessController) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) Security(org.codice.ddf.security.Security) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) DeleteResponse(ddf.catalog.operation.DeleteResponse) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) Update(ddf.catalog.operation.Update) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) SKIP_VERSIONING(ddf.catalog.core.versioning.MetacardVersion.SKIP_VERSIONING) ContentItem(ddf.catalog.content.data.ContentItem) CreateResponse(ddf.catalog.operation.CreateResponse) Metacard(ddf.catalog.data.Metacard) SecurityConstants(ddf.security.SecurityConstants) StorageProvider(ddf.catalog.content.StorageProvider) ByteSource(com.google.common.io.ByteSource) Result(ddf.catalog.data.Result) Hashtable(java.util.Hashtable) Nullable(javax.annotation.Nullable) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) QueryImpl(ddf.catalog.operation.impl.QueryImpl) SubjectIdentity(ddf.security.SubjectIdentity) Logger(org.slf4j.Logger) SecurityLogger(ddf.security.audit.SecurityLogger) IngestException(ddf.catalog.source.IngestException) Subject(ddf.security.Subject) IOException(java.io.IOException) ReadStorageRequestImpl(ddf.catalog.content.operation.impl.ReadStorageRequestImpl) TimeUnit(java.util.concurrent.TimeUnit) SourceResponse(ddf.catalog.operation.SourceResponse) CatalogProvider(ddf.catalog.source.CatalogProvider) Filter(org.opengis.filter.Filter) Collections(java.util.Collections) FrameworkUtil(org.osgi.framework.FrameworkUtil) ReadStorageResponse(ddf.catalog.content.operation.ReadStorageResponse) InputStream(java.io.InputStream) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) Action(ddf.catalog.core.versioning.MetacardVersion.Action) PrivilegedAction(java.security.PrivilegedAction) CreateResponse(ddf.catalog.operation.CreateResponse) CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Metacard(ddf.catalog.data.Metacard) ReadStorageRequest(ddf.catalog.content.operation.ReadStorageRequest) Objects(java.util.Objects) List(java.util.List) ArrayList(java.util.ArrayList) ContentItem(ddf.catalog.content.data.ContentItem)

Aggregations

CreateResponse (ddf.catalog.operation.CreateResponse)111 Test (org.junit.Test)82 Metacard (ddf.catalog.data.Metacard)76 CreateRequestImpl (ddf.catalog.operation.impl.CreateRequestImpl)44 ArrayList (java.util.ArrayList)42 CreateRequest (ddf.catalog.operation.CreateRequest)36 QueryImpl (ddf.catalog.operation.impl.QueryImpl)29 QueryRequestImpl (ddf.catalog.operation.impl.QueryRequestImpl)29 CreateResponseImpl (ddf.catalog.operation.impl.CreateResponseImpl)27 HashMap (java.util.HashMap)25 Serializable (java.io.Serializable)23 List (java.util.List)23 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)22 DeleteResponse (ddf.catalog.operation.DeleteResponse)22 UpdateResponse (ddf.catalog.operation.UpdateResponse)21 Filter (org.opengis.filter.Filter)21 IngestException (ddf.catalog.source.IngestException)20 SourceResponse (ddf.catalog.operation.SourceResponse)18 QueryRequest (ddf.catalog.operation.QueryRequest)17 MetacardType (ddf.catalog.data.MetacardType)16