Search in sources :

Example 11 with CreateStorageRequestImpl

use of ddf.catalog.content.operation.impl.CreateStorageRequestImpl in project ddf by codice.

the class CatalogFrameworkImplTest method testUpdateItemWithQualifier.

/**
     * Tests that the framework properly passes an update request to the local provider when the
     * content item has a qualifier.
     */
@Test
public void testUpdateItemWithQualifier() throws Exception {
    // store one item
    MetacardImpl metacard = new MetacardImpl();
    ByteSource byteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return new ByteArrayInputStream("blah".getBytes());
        }
    };
    ContentItemImpl contentItem = new ContentItemImpl(uuidGenerator.generateUuid(), byteSource, "application/octet-stream", "blah", 0L, metacard);
    CreateResponse response = framework.create(new CreateStorageRequestImpl(Collections.singletonList(contentItem), null));
    Metacard createResponseMetacard = response.getCreatedMetacards().get(0);
    // update with 2 more content items that have a qualifier and the same id and metacard as the already-created item
    List<ContentItem> updateRequestContentItems = new ArrayList<>();
    ByteSource q1ByteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return new ByteArrayInputStream("q1 data".getBytes());
        }
    };
    ContentItem q1ContentItem = new ContentItemImpl(createResponseMetacard.getId(), "q1", q1ByteSource, "application/octet-stream", createResponseMetacard);
    updateRequestContentItems.add(q1ContentItem);
    ByteSource q2ByteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return new ByteArrayInputStream("q2 data".getBytes());
        }
    };
    ContentItem q2ContentItem = new ContentItemImpl(createResponseMetacard.getId(), "q2", q2ByteSource, "application/octet-stream", createResponseMetacard);
    updateRequestContentItems.add(q2ContentItem);
    UpdateStorageRequest request = new UpdateStorageRequestImpl(updateRequestContentItems, null);
    List<Result> mockFederationResults = Stream.of(createResponseMetacard).map(m -> {
        Result mockResult = mock(Result.class);
        when(mockResult.getMetacard()).thenReturn(m);
        return mockResult;
    }).collect(Collectors.toList());
    QueryResponseImpl queryResponse = new QueryResponseImpl(mock(QueryRequest.class), mockFederationResults, 1);
    when(mockFederationStrategy.federate(anyList(), anyObject())).thenReturn(queryResponse);
    // send update to framework
    List<Update> returnedCards = framework.update(request).getUpdatedMetacards();
    assertThat(returnedCards, hasSize(1));
    final Metacard updateResponseMetacard = returnedCards.get(0).getNewMetacard();
    assertThat(updateResponseMetacard.getId(), notNullValue());
    assertThat(updateResponseMetacard.getResourceURI().toString(), is(contentItem.getUri()));
    assertThat(updateResponseMetacard.getResourceSize(), is(Long.toString(byteSource.size())));
    assertThat(response.getCreatedMetacards(), hasSize(storageProvider.size()));
    // make sure that the event was posted correctly
    assertThat(eventAdmin.wasEventPosted(), is(true));
}
Also used : Arrays(java.util.Arrays) StringUtils(org.apache.commons.lang.StringUtils) AttributeRegistryImpl(ddf.catalog.data.impl.AttributeRegistryImpl) MetacardTypeImpl(ddf.catalog.data.impl.MetacardTypeImpl) CreateRequest(ddf.catalog.operation.CreateRequest) BinaryContent(ddf.catalog.data.BinaryContent) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) AttributeType(ddf.catalog.data.AttributeType) FilterFactory(org.opengis.filter.FilterFactory) PluginExecutionException(ddf.catalog.plugin.PluginExecutionException) UpdateOperations(ddf.catalog.impl.operations.UpdateOperations) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) AttributeDescriptorImpl(ddf.catalog.data.impl.AttributeDescriptorImpl) CreateOperations(ddf.catalog.impl.operations.CreateOperations) RemoteDeleteOperations(ddf.catalog.impl.operations.RemoteDeleteOperations) ServiceReference(org.osgi.framework.ServiceReference) InputTransformer(ddf.catalog.transform.InputTransformer) PostResourcePlugin(ddf.catalog.plugin.PostResourcePlugin) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Set(java.util.Set) SourceOperations(ddf.catalog.impl.operations.SourceOperations) MimeTypeResolver(ddf.mime.MimeTypeResolver) Serializable(java.io.Serializable) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) Matchers.any(org.mockito.Matchers.any) SourceInfoRequest(ddf.catalog.operation.SourceInfoRequest) BASIC_METACARD(ddf.catalog.data.impl.BasicTypes.BASIC_METACARD) Stream(java.util.stream.Stream) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) Assert.assertFalse(org.junit.Assert.assertFalse) QueryResponseTransformer(ddf.catalog.transform.QueryResponseTransformer) Matchers.is(org.hamcrest.Matchers.is) UpdateResponse(ddf.catalog.operation.UpdateResponse) BasicTypes(ddf.catalog.data.impl.BasicTypes) FilterFactoryImpl(org.geotools.filter.FilterFactoryImpl) Mockito.mock(org.mockito.Mockito.mock) ResourceResponse(ddf.catalog.operation.ResourceResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) PostQueryPlugin(ddf.catalog.plugin.PostQueryPlugin) AdditionalAnswers.returnsSecondArg(org.mockito.AdditionalAnswers.returnsSecondArg) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) CatalogFramework(ddf.catalog.CatalogFramework) QueryResponseImpl(ddf.catalog.operation.impl.QueryResponseImpl) DeleteResponse(ddf.catalog.operation.DeleteResponse) Mockito.spy(org.mockito.Mockito.spy) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) DefaultAttributeValueRegistryImpl(ddf.catalog.data.defaultvalues.DefaultAttributeValueRegistryImpl) Resource(ddf.catalog.resource.Resource) PostIngestPlugin(ddf.catalog.plugin.PostIngestPlugin) Source(ddf.catalog.source.Source) GeotoolsFilterAdapterImpl(ddf.catalog.filter.proxy.adapter.GeotoolsFilterAdapterImpl) TestWatchman(org.junit.rules.TestWatchman) ContentItem(ddf.catalog.content.data.ContentItem) OperationsStorageSupport(ddf.catalog.impl.operations.OperationsStorageSupport) SourcePollerRunner(ddf.catalog.util.impl.SourcePollerRunner) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ResourceRequest(ddf.catalog.operation.ResourceRequest) QueryRequest(ddf.catalog.operation.QueryRequest) SourceInfoRequestSources(ddf.catalog.operation.impl.SourceInfoRequestSources) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ByteSource(com.google.common.io.ByteSource) Result(ddf.catalog.data.Result) TransformOperations(ddf.catalog.impl.operations.TransformOperations) Before(org.junit.Before) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) ContentType(ddf.catalog.data.ContentType) ResourceOperations(ddf.catalog.impl.operations.ResourceOperations) Historian(ddf.catalog.history.Historian) IngestException(ddf.catalog.source.IngestException) Assert.assertTrue(org.junit.Assert.assertTrue) StopProcessingException(ddf.catalog.plugin.StopProcessingException) IOException(java.io.IOException) Test(org.junit.Test) Subject(ddf.security.Subject) AttributeInjector(ddf.catalog.data.AttributeInjector) FederationException(ddf.catalog.federation.FederationException) AttributeInjectorImpl(ddf.catalog.data.inject.AttributeInjectorImpl) DAYS(java.time.temporal.ChronoUnit.DAYS) Query(ddf.catalog.operation.Query) ValidationQueryFactory(ddf.catalog.cache.solr.impl.ValidationQueryFactory) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Assert.assertEquals(org.junit.Assert.assertEquals) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) PreQueryPlugin(ddf.catalog.plugin.PreQueryPlugin) CatalogStore(ddf.catalog.source.CatalogStore) DeleteOperations(ddf.catalog.impl.operations.DeleteOperations) Date(java.util.Date) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) URISyntaxException(java.net.URISyntaxException) MethodRule(org.junit.rules.MethodRule) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) IsEqual.equalTo(org.hamcrest.core.IsEqual.equalTo) LoggerFactory(org.slf4j.LoggerFactory) ResourceCacheImpl(ddf.catalog.cache.impl.ResourceCacheImpl) SourceDescriptor(ddf.catalog.source.SourceDescriptor) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) Assert.fail(org.junit.Assert.fail) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) URI(java.net.URI) CachedSource(ddf.catalog.util.impl.CachedSource) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) MetacardFactory(ddf.catalog.impl.operations.MetacardFactory) Matchers.isA(org.mockito.Matchers.isA) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) FederatedSource(ddf.catalog.source.FederatedSource) MimeTypeToTransformerMapper(ddf.mime.MimeTypeToTransformerMapper) ResultImpl(ddf.catalog.data.impl.ResultImpl) SourceInfoRequestEnterprise(ddf.catalog.operation.impl.SourceInfoRequestEnterprise) ResourceReader(ddf.catalog.resource.ResourceReader) UUID(java.util.UUID) SourceMonitor(ddf.catalog.source.SourceMonitor) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) BundleContext(org.osgi.framework.BundleContext) Sets(com.google.common.collect.Sets) MetacardType(ddf.catalog.data.MetacardType) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) DeleteRequest(ddf.catalog.operation.DeleteRequest) QueryResponse(ddf.catalog.operation.QueryResponse) List(java.util.List) GeotoolsFilterBuilder(ddf.catalog.filter.proxy.builder.GeotoolsFilterBuilder) MimeTypeMapperImpl(ddf.mime.mapper.MimeTypeMapperImpl) Matchers.anyMap(org.mockito.Matchers.anyMap) Entry(java.util.Map.Entry) FederationStrategy(ddf.catalog.federation.FederationStrategy) FilterBuilder(ddf.catalog.filter.FilterBuilder) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) HashMap(java.util.HashMap) Update(ddf.catalog.operation.Update) DefaultAttributeValueRegistry(ddf.catalog.data.DefaultAttributeValueRegistry) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) CreateResponse(ddf.catalog.operation.CreateResponse) CollectionUtils(org.apache.commons.collections.CollectionUtils) Constants(ddf.catalog.Constants) Metacard(ddf.catalog.data.Metacard) Matchers.anyObject(org.mockito.Matchers.anyObject) MimeType(javax.activation.MimeType) SourcePoller(ddf.catalog.util.impl.SourcePoller) SecurityConstants(ddf.security.SecurityConstants) StorageProvider(ddf.catalog.content.StorageProvider) OperationsCatalogStoreSupport(ddf.catalog.impl.operations.OperationsCatalogStoreSupport) UpdateRequest(ddf.catalog.operation.UpdateRequest) SimpleEntry(java.util.AbstractMap.SimpleEntry) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) QueryImpl(ddf.catalog.operation.impl.QueryImpl) FrameworkMethod(org.junit.runners.model.FrameworkMethod) Logger(org.slf4j.Logger) Assert.assertNotNull(org.junit.Assert.assertNotNull) OperationsMetacardSupport(ddf.catalog.impl.operations.OperationsMetacardSupport) Mockito.when(org.mockito.Mockito.when) OperationsSecuritySupport(ddf.catalog.impl.operations.OperationsSecuritySupport) Mockito.verify(org.mockito.Mockito.verify) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) MockMemoryStorageProvider(ddf.catalog.content.impl.MockMemoryStorageProvider) SourceResponse(ddf.catalog.operation.SourceResponse) Rule(org.junit.Rule) Ignore(org.junit.Ignore) CatalogProvider(ddf.catalog.source.CatalogProvider) ThreadContext(org.apache.shiro.util.ThreadContext) QueryOperations(ddf.catalog.impl.operations.QueryOperations) Filter(org.opengis.filter.Filter) Matchers.anyList(org.mockito.Matchers.anyList) Collections(java.util.Collections) InputStream(java.io.InputStream) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) QueryRequest(ddf.catalog.operation.QueryRequest) CreateResponse(ddf.catalog.operation.CreateResponse) ArrayList(java.util.ArrayList) Update(ddf.catalog.operation.Update) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Result(ddf.catalog.data.Result) Metacard(ddf.catalog.data.Metacard) QueryResponseImpl(ddf.catalog.operation.impl.QueryResponseImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) ByteSource(com.google.common.io.ByteSource) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) Test(org.junit.Test)

Example 12 with CreateStorageRequestImpl

use of ddf.catalog.content.operation.impl.CreateStorageRequestImpl in project ddf by codice.

the class CatalogFrameworkImplTest method testCreateStorageWithAttributeOverrides.

/**
     * Tests that the framework properly passes a create request to the local provider with attribute overrides.
     */
@Test
public void testCreateStorageWithAttributeOverrides() throws Exception {
    List<ContentItem> contentItems = new ArrayList<>();
    Map<String, Serializable> propertiesMap = new HashMap<>();
    HashMap<String, String> attributeMap = new HashMap<>();
    attributeMap.put(Metacard.TITLE, "test");
    attributeMap.put("foo", "bar");
    propertiesMap.put(Constants.ATTRIBUTE_OVERRIDES_KEY, attributeMap);
    MetacardImpl newCard = new MetacardImpl();
    newCard.setId(null);
    MetacardType metacardType = mock(MetacardType.class);
    AttributeDescriptor stringAttributeDescriptor = new AttributeDescriptorImpl(Metacard.TITLE, true, true, true, true, new AttributeType<String>() {

        private static final long serialVersionUID = 1L;

        @Override
        public Class<String> getBinding() {
            return String.class;
        }

        @Override
        public AttributeFormat getAttributeFormat() {
            return AttributeFormat.STRING;
        }
    });
    when(metacardType.getAttributeDescriptor(Metacard.TITLE)).thenReturn(stringAttributeDescriptor);
    newCard.setType(metacardType);
    ByteSource byteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return new ByteArrayInputStream("blah".getBytes());
        }
    };
    ContentItemImpl newItem = new ContentItemImpl(uuidGenerator.generateUuid(), byteSource, "application/octet-stream", "blah", 0L, newCard);
    contentItems.add(newItem);
    CreateResponse response = framework.create(new CreateStorageRequestImpl(contentItems, propertiesMap));
    assertEquals(response.getCreatedMetacards().size(), provider.size());
    assertEquals(response.getCreatedMetacards().size(), storageProvider.size());
    for (Metacard curCard : response.getCreatedMetacards()) {
        assertNotNull(curCard.getId());
        // Assert valid attribute is set for the metacard
        assertThat(curCard.getTitle(), is("test"));
        // Assert invalid attribute is not set for the metacard
        assertThat(curCard.getAttribute("foo"), nullValue());
    }
    // Assert That Attribute Overrides do not exist after create
    assertThat(attributeMap.get(Constants.ATTRIBUTE_OVERRIDES_KEY), nullValue());
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) CreateResponse(ddf.catalog.operation.CreateResponse) ArrayList(java.util.ArrayList) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) Matchers.anyString(org.mockito.Matchers.anyString) AttributeDescriptorImpl(ddf.catalog.data.impl.AttributeDescriptorImpl) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) MetacardType(ddf.catalog.data.MetacardType) Metacard(ddf.catalog.data.Metacard) ByteArrayInputStream(java.io.ByteArrayInputStream) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) ByteSource(com.google.common.io.ByteSource) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) Test(org.junit.Test)

Example 13 with CreateStorageRequestImpl

use of ddf.catalog.content.operation.impl.CreateStorageRequestImpl in project ddf by codice.

the class CatalogFrameworkImplTest method testCreateStorage.

/**
     * Tests that the framework properly passes a create request to the local provider.
     */
@Test
public void testCreateStorage() throws Exception {
    List<ContentItem> contentItems = new ArrayList<>();
    MetacardImpl newCard = new MetacardImpl();
    newCard.setId(null);
    ByteSource byteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return new ByteArrayInputStream("blah".getBytes());
        }
    };
    ContentItemImpl newItem = new ContentItemImpl(uuidGenerator.generateUuid(), byteSource, "application/octet-stream", "blah", 0L, newCard);
    contentItems.add(newItem);
    CreateResponse response = framework.create(new CreateStorageRequestImpl(contentItems, null));
    assertEquals(response.getCreatedMetacards().size(), provider.size());
    assertEquals(response.getCreatedMetacards().size(), storageProvider.size());
    for (Metacard curCard : response.getCreatedMetacards()) {
        assertNotNull(curCard.getId());
    }
    // make sure that the event was posted correctly
    assertTrue(eventAdmin.wasEventPosted());
    Metacard[] array = {};
    array = response.getCreatedMetacards().toArray(array);
    assertTrue(eventAdmin.wasEventPosted());
    assertEquals(eventAdmin.getLastEvent(), array[array.length - 1]);
}
Also used : Metacard(ddf.catalog.data.Metacard) ByteArrayInputStream(java.io.ByteArrayInputStream) CreateResponse(ddf.catalog.operation.CreateResponse) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) ArrayList(java.util.ArrayList) ByteSource(com.google.common.io.ByteSource) ContentItem(ddf.catalog.content.data.ContentItem) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) Test(org.junit.Test)

Example 14 with CreateStorageRequestImpl

use of ddf.catalog.content.operation.impl.CreateStorageRequestImpl in project ddf by codice.

the class ImportCommand method executeWithSubject.

@Override
protected Object executeWithSubject() throws Exception {
    int metacards = 0;
    int content = 0;
    int derivedContent = 0;
    ZipValidator zipValidator = initZipValidator();
    File file = initImportFile(importFile);
    InputTransformer transformer = getServiceByFilter(InputTransformer.class, String.format("(%s=%s)", "id", DEFAULT_TRANSFORMER_ID)).orElseThrow(() -> new CatalogCommandRuntimeException("Could not get " + DEFAULT_TRANSFORMER_ID + " input transformer"));
    if (unsafe) {
        if (!force) {
            console.println("This will import data with no check to see if data is modified/corrupt. Do you wish to continue?");
            String input = getUserInputModifiable().toString();
            if (!input.matches("^[yY][eE]?[sS]?$")) {
                console.println("ABORTED IMPORT.");
                return null;
            }
        }
        SecurityLogger.audit("Skipping validation check of imported data. There are no " + "guarantees of integrity or authenticity of the imported data." + "File being imported: {}", importFile);
    } else {
        if (!zipValidator.validateZipFile(importFile)) {
            throw new CatalogCommandRuntimeException("Signature on zip file is not valid");
        }
    }
    SecurityLogger.audit("Called catalog:import command on the file: {}", importFile);
    console.println("Importing file");
    Instant start = Instant.now();
    try (InputStream fis = new FileInputStream(file);
        ZipInputStream zipInputStream = new ZipInputStream(fis)) {
        ZipEntry entry = zipInputStream.getNextEntry();
        while (entry != null) {
            String filename = entry.getName();
            if (filename.startsWith("META-INF")) {
                entry = zipInputStream.getNextEntry();
                continue;
            }
            String[] pathParts = filename.split("\\" + File.separator);
            if (pathParts.length < 5) {
                console.println("Entry is not valid! " + filename);
                entry = zipInputStream.getNextEntry();
                continue;
            }
            String id = pathParts[ID];
            String type = pathParts[TYPE];
            switch(type) {
                case "metacard":
                    {
                        metacards++;
                        String metacardName = pathParts[NAME];
                        Metacard metacard = null;
                        try {
                            metacard = transformer.transform(new UncloseableBufferedInputStreamWrapper(zipInputStream), id);
                        } catch (IOException | CatalogTransformerException e) {
                            LOGGER.debug("Could not transform metacard: {}", id);
                        }
                        catalogProvider.create(new CreateRequestImpl(metacard));
                        break;
                    }
                case "content":
                    {
                        content++;
                        String contentFilename = pathParts[NAME];
                        ContentItem contentItem = new ContentItemImpl(id, new ZipEntryByteSource(new UncloseableBufferedInputStreamWrapper(zipInputStream)), null, contentFilename, entry.getSize(), null);
                        CreateStorageRequestImpl createStorageRequest = new CreateStorageRequestImpl(Collections.singletonList(contentItem), id, new HashMap<>());
                        storageProvider.create(createStorageRequest);
                        storageProvider.commit(createStorageRequest);
                        break;
                    }
                case "derived":
                    {
                        derivedContent++;
                        String qualifier = pathParts[NAME];
                        String derivedContentName = pathParts[DERIVED_NAME];
                        ContentItem contentItem = new ContentItemImpl(id, qualifier, new ZipEntryByteSource(new UncloseableBufferedInputStreamWrapper(zipInputStream)), null, derivedContentName, entry.getSize(), null);
                        CreateStorageRequestImpl createStorageRequest = new CreateStorageRequestImpl(Collections.singletonList(contentItem), id, new HashMap<>());
                        storageProvider.create(createStorageRequest);
                        storageProvider.commit(createStorageRequest);
                        break;
                    }
                default:
                    {
                        LOGGER.debug("Cannot interpret type of {}", type);
                    }
            }
            entry = zipInputStream.getNextEntry();
        }
    } catch (Exception e) {
        printErrorMessage(String.format("Exception while importing metacards (%s)%nFor more information set the log level to INFO (log:set INFO org.codice.ddf.commands.catalog) ", e.getMessage()));
        LOGGER.info("Exception while importing metacards", e);
        throw e;
    }
    console.println("File imported successfully. Imported in: " + getFormattedDuration(start));
    console.println("Number of metacards imported: " + metacards);
    console.println("Number of content imported: " + content);
    console.println("Number of derived content imported: " + derivedContent);
    return null;
}
Also used : HashMap(java.util.HashMap) BufferedInputStream(java.io.BufferedInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Instant(java.time.Instant) ZipEntry(java.util.zip.ZipEntry) CatalogCommandRuntimeException(org.codice.ddf.commands.util.CatalogCommandRuntimeException) InputTransformer(ddf.catalog.transform.InputTransformer) FileInputStream(java.io.FileInputStream) CatalogCommandRuntimeException(org.codice.ddf.commands.util.CatalogCommandRuntimeException) IOException(java.io.IOException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ZipInputStream(java.util.zip.ZipInputStream) Metacard(ddf.catalog.data.Metacard) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) File(java.io.File) ZipValidator(org.codice.ddf.catalog.transformer.zip.ZipValidator) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl)

Example 15 with CreateStorageRequestImpl

use of ddf.catalog.content.operation.impl.CreateStorageRequestImpl in project ddf by codice.

the class IngestCommand method submitToStorageProvider.

private void submitToStorageProvider(List<Metacard> metacardList) {
    metacardList.stream().filter(metacard -> metacardFileMapping.containsKey(metacard.getId())).map(metacard -> {
        List<File> fileList = metacardFileMapping.get(metacard.getId());
        List<ContentItem> contentItemList = new ArrayList<>();
        ContentItem contentItem;
        for (File file : fileList) {
            ByteSource byteSource = com.google.common.io.Files.asByteSource(file);
            String fileName = file.getName().split("-")[1];
            String fragment = null;
            if (!file.getPath().contains(CONTENT + File.separator + metacard.getId())) {
                fragment = StringUtils.substringBetween(file.getPath(), CONTENT + File.separator, File.separator + metacard.getId());
            }
            contentItem = new ContentItemImpl(metacard.getId(), fragment, byteSource, metacard.getContentTypeName(), fileName, file.length(), metacard);
            contentItemList.add(contentItem);
        }
        return new CreateStorageRequestImpl(contentItemList, metacard.getId(), new HashMap<>());
    }).forEach(createStorageRequest -> {
        try {
            storageProvider.create(createStorageRequest);
            storageProvider.commit(createStorageRequest);
        } catch (StorageException e) {
            LOGGER.debug("Unable to create content for {}", createStorageRequest.getId(), e);
            try {
                storageProvider.rollback(createStorageRequest);
            } catch (StorageException e1) {
                LOGGER.debug("Unable to perform rollback on temporary content for {} ", createStorageRequest.getId(), e1);
            }
        }
    });
}
Also used : Ansi(org.fusesource.jansi.Ansi) StringUtils(org.apache.commons.lang.StringUtils) CreateRequest(ddf.catalog.operation.CreateRequest) ObjectInputStream(java.io.ObjectInputStream) LoggerFactory(org.slf4j.LoggerFactory) SecurityLogger(ddf.security.common.audit.SecurityLogger) Command(org.apache.karaf.shell.api.action.Command) DirectoryStream(java.nio.file.DirectoryStream) RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Path(java.nio.file.Path) InputTransformer(ddf.catalog.transform.InputTransformer) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BlockingQueue(java.util.concurrent.BlockingQueue) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Serializable(java.io.Serializable) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) FileVisitResult(java.nio.file.FileVisitResult) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) StorageException(ddf.catalog.content.StorageException) List(java.util.List) Stream(java.util.stream.Stream) PeriodFormatterBuilder(org.joda.time.format.PeriodFormatterBuilder) Optional(java.util.Optional) FilenameUtils(org.apache.commons.io.FilenameUtils) IntStream(java.util.stream.IntStream) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) HashMap(java.util.HashMap) PeriodFormatter(org.joda.time.format.PeriodFormatter) ArrayList(java.util.ArrayList) Reference(org.apache.karaf.shell.api.action.lifecycle.Reference) ContentItem(ddf.catalog.content.data.ContentItem) CreateResponse(ddf.catalog.operation.CreateResponse) Constants(ddf.catalog.Constants) Metacard(ddf.catalog.data.Metacard) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) StorageProvider(ddf.catalog.content.StorageProvider) Exceptions(org.codice.ddf.platform.util.Exceptions) ByteSource(com.google.common.io.ByteSource) ExecutorService(java.util.concurrent.ExecutorService) Period(org.joda.time.Period) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) Logger(org.slf4j.Logger) Files(java.nio.file.Files) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) Argument(org.apache.karaf.shell.api.action.Argument) FileInputStream(java.io.FileInputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) FileVisitOption(java.nio.file.FileVisitOption) Paths(java.nio.file.Paths) Phaser(java.util.concurrent.Phaser) Service(org.apache.karaf.shell.api.action.lifecycle.Service) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade) Option(org.apache.karaf.shell.api.action.Option) InputCollectionTransformer(ddf.catalog.transform.InputCollectionTransformer) InputStream(java.io.InputStream) HashMap(java.util.HashMap) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) ByteSource(com.google.common.io.ByteSource) List(java.util.List) ArrayList(java.util.ArrayList) File(java.io.File) StorageException(ddf.catalog.content.StorageException) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl)

Aggregations

CreateStorageRequestImpl (ddf.catalog.content.operation.impl.CreateStorageRequestImpl)17 ContentItem (ddf.catalog.content.data.ContentItem)14 ContentItemImpl (ddf.catalog.content.data.impl.ContentItemImpl)14 Metacard (ddf.catalog.data.Metacard)13 ByteSource (com.google.common.io.ByteSource)9 CreateResponse (ddf.catalog.operation.CreateResponse)9 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)8 Test (org.junit.Test)8 CreateStorageRequest (ddf.catalog.content.operation.CreateStorageRequest)7 CreateRequestImpl (ddf.catalog.operation.impl.CreateRequestImpl)6 Serializable (java.io.Serializable)6 CreateStorageResponse (ddf.catalog.content.operation.CreateStorageResponse)5 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)5 CreateRequest (ddf.catalog.operation.CreateRequest)5 IngestException (ddf.catalog.source.IngestException)5 IOException (java.io.IOException)5 StorageProvider (ddf.catalog.content.StorageProvider)4 UpdateStorageRequestImpl (ddf.catalog.content.operation.impl.UpdateStorageRequestImpl)4 InputTransformer (ddf.catalog.transform.InputTransformer)4