Search in sources :

Example 56 with ContentItem

use of ddf.catalog.content.data.ContentItem 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 57 with ContentItem

use of ddf.catalog.content.data.ContentItem 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)

Example 58 with ContentItem

use of ddf.catalog.content.data.ContentItem in project ddf by codice.

the class OperationsMetacardSupport method generateMetacardAndContentItems.

void generateMetacardAndContentItems(List<ContentItem> incomingContentItems, Map<String, Metacard> metacardMap, List<ContentItem> contentItems, Map<String, Map<String, Path>> tmpContentPaths) throws IngestException {
    for (ContentItem contentItem : incomingContentItems) {
        try {
            Path tmpPath = null;
            long size;
            try (InputStream inputStream = contentItem.getInputStream()) {
                if (inputStream == null) {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }
                String sanitizedFilename = InputValidation.sanitizeFilename(contentItem.getFilename());
                tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename), FilenameUtils.getExtension(sanitizedFilename));
                Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING);
                size = Files.size(tmpPath);
                final String key = contentItem.getId();
                Map<String, Path> pathAndQualifiers = tmpContentPaths.get(key);
                if (pathAndQualifiers == null) {
                    pathAndQualifiers = new HashMap<>();
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                    tmpContentPaths.put(key, pathAndQualifiers);
                } else {
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                }
            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, contentItem.getFilename(), tmpPath);
            if (!InputValidation.checkForClientSideVulnerableMimeType(mimeTypeRaw)) {
                throw new IngestException("Unsupported mime type.");
            }
            String fileName = updateFileExtension(mimeTypeRaw, contentItem.getFilename());
            Metacard metacard = metacardFactory.generateMetacard(mimeTypeRaw, contentItem.getId(), fileName, tmpPath);
            metacardMap.put(metacard.getId(), metacard);
            ContentItem generatedContentItem = new ContentItemImpl(metacard.getId(), StringUtils.isNotEmpty(contentItem.getQualifier()) ? contentItem.getQualifier() : "", com.google.common.io.Files.asByteSource(tmpPath.toFile()), mimeTypeRaw, fileName, size, metacard);
            contentItems.add(generatedContentItem);
        } catch (Exception e) {
            tmpContentPaths.values().stream().flatMap(id -> id.values().stream()).forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}
Also used : Path(java.nio.file.Path) DefaultProbDetector(org.apache.tika.detect.DefaultProbDetector) StringUtils(org.apache.commons.lang.StringUtils) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) LoggerFactory(org.slf4j.LoggerFactory) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) HashMap(java.util.HashMap) MediaType(org.apache.tika.mime.MediaType) DefaultAttributeValueRegistry(ddf.catalog.data.DefaultAttributeValueRegistry) StandardCopyOption(java.nio.file.StandardCopyOption) Metadata(org.apache.tika.metadata.Metadata) Charset(java.nio.charset.Charset) ContentItem(ddf.catalog.content.data.ContentItem) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) TikaInputStream(org.apache.tika.io.TikaInputStream) Path(java.nio.file.Path) Logger(org.slf4j.Logger) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) Files(java.nio.file.Files) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Detector(org.apache.tika.detect.Detector) AttributeInjector(ddf.catalog.data.AttributeInjector) InputStreamReader(java.io.InputStreamReader) FrameworkProperties(ddf.catalog.impl.FrameworkProperties) MimeTypeResolutionException(ddf.mime.MimeTypeResolutionException) MetacardType(ddf.catalog.data.MetacardType) List(java.util.List) Attribute(ddf.catalog.data.Attribute) InputValidation(org.codice.ddf.platform.util.InputValidation) BufferedReader(java.io.BufferedReader) FilenameUtils(org.apache.commons.io.FilenameUtils) InputStream(java.io.InputStream) TikaInputStream(org.apache.tika.io.TikaInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) MimeTypeResolutionException(ddf.mime.MimeTypeResolutionException) Metacard(ddf.catalog.data.Metacard) IngestException(ddf.catalog.source.IngestException) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl)

Example 59 with ContentItem

use of ddf.catalog.content.data.ContentItem in project ddf by codice.

the class FileSystemStorageProviderTest method testRollback.

@Test(expected = StorageException.class)
public void testRollback() throws Exception {
    String id = UUID.randomUUID().toString().replaceAll("-", "");
    ByteSource byteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return IOUtils.toInputStream(TEST_INPUT_CONTENTS);
        }
    };
    Metacard metacard = mock(Metacard.class);
    when(metacard.getId()).thenReturn(id);
    ContentItem contentItem = new ContentItemImpl(id, byteSource, NITF_MIME_TYPE, TEST_INPUT_FILENAME, TEST_INPUT_CONTENTS.getBytes().length, metacard);
    CreateStorageRequest createRequest = new CreateStorageRequestImpl(Collections.singletonList(contentItem), null);
    CreateStorageResponse createStorageResponse = provider.create(createRequest);
    provider.rollback(createRequest);
    ReadStorageRequest readStorageRequest = new ReadStorageRequestImpl(new URI("content:" + id), null);
    ReadStorageResponse read = provider.read(readStorageRequest);
}
Also used : CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Metacard(ddf.catalog.data.Metacard) ReadStorageRequest(ddf.catalog.content.operation.ReadStorageRequest) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) ByteSource(com.google.common.io.ByteSource) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) ReadStorageRequestImpl(ddf.catalog.content.operation.impl.ReadStorageRequestImpl) ReadStorageResponse(ddf.catalog.content.operation.ReadStorageResponse) URI(java.net.URI) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest) Test(org.junit.Test)

Example 60 with ContentItem

use of ddf.catalog.content.data.ContentItem in project ddf by codice.

the class FileSystemStorageProviderTest method submitAndVerifySuccessfulUpdateStorageRequest.

private void submitAndVerifySuccessfulUpdateStorageRequest(ContentItem... requestContentItems) throws Exception {
    final UpdateStorageRequest updateStorageRequest = new UpdateStorageRequestImpl(Arrays.asList(requestContentItems), null);
    final UpdateStorageResponse updateStorageResponse = provider.update(updateStorageRequest);
    final List<ContentItem> responseContentItems = updateStorageResponse.getUpdatedContentItems();
    assertThat("Expect number of ContentItems in UpdateStorageResponse", responseContentItems, hasSize(requestContentItems.length));
    for (final ContentItem responseContentItem : responseContentItems) {
        // assert file exists
        final URI uri = new URI(responseContentItem.getUri());
        final List<String> parts = provider.getContentFilePathParts(uri.getSchemeSpecificPart(), uri.getFragment());
        final String expectedFilePath = baseDir + File.separator + FileSystemStorageProvider.DEFAULT_CONTENT_REPOSITORY + File.separator + FileSystemStorageProvider.DEFAULT_CONTENT_STORE + File.separator + FileSystemStorageProvider.DEFAULT_TMP + File.separator + updateStorageRequest.getId() + File.separator + parts.get(0) + File.separator + parts.get(1) + File.separator + parts.get(2) + (StringUtils.isNotBlank(responseContentItem.getQualifier()) ? File.separator + responseContentItem.getQualifier() : "") + File.separator + responseContentItem.getFilename();
        assertThat("Expect file exists at " + expectedFilePath, Files.exists(Paths.get(expectedFilePath)));
        // assert metacard attributes set
        final ArgumentCaptor<Attribute> captor = ArgumentCaptor.forClass(Attribute.class);
        final Metacard metacard = responseContentItem.getMetacard();
        if (StringUtils.isBlank(responseContentItem.getQualifier())) {
            verify(metacard, times(2)).setAttribute(captor.capture());
            Attribute resourceUriAttribute = captor.getAllValues().get(0);
            assertThat(resourceUriAttribute.getName(), is(Metacard.RESOURCE_URI));
            assertThat(resourceUriAttribute.getValue(), is(uri.toString()));
            Attribute resourceSizeAttribute = captor.getAllValues().get(1);
            assertThat(resourceSizeAttribute.getName(), is(Metacard.RESOURCE_SIZE));
            assertThat(resourceSizeAttribute.getValue(), is(responseContentItem.getSize()));
        } else {
            verify(metacard, never()).setAttribute(any());
        }
    }
    provider.commit(updateStorageRequest);
    for (ContentItem responseContentItem : responseContentItems) {
        assertReadRequest(responseContentItem.getUri(), responseContentItem.getMimeType().toString());
    }
}
Also used : Metacard(ddf.catalog.data.Metacard) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) Attribute(ddf.catalog.data.Attribute) UpdateStorageResponse(ddf.catalog.content.operation.UpdateStorageResponse) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) URI(java.net.URI) ContentItem(ddf.catalog.content.data.ContentItem)

Aggregations

ContentItem (ddf.catalog.content.data.ContentItem)65 Metacard (ddf.catalog.data.Metacard)37 Test (org.junit.Test)36 ContentItemImpl (ddf.catalog.content.data.impl.ContentItemImpl)27 ArrayList (java.util.ArrayList)22 CreateStorageResponse (ddf.catalog.content.operation.CreateStorageResponse)20 HashMap (java.util.HashMap)19 URI (java.net.URI)17 ByteSource (com.google.common.io.ByteSource)16 CreateStorageRequestImpl (ddf.catalog.content.operation.impl.CreateStorageRequestImpl)16 Matchers.isEmptyString (org.hamcrest.Matchers.isEmptyString)15 IOException (java.io.IOException)14 UpdateStorageRequest (ddf.catalog.content.operation.UpdateStorageRequest)13 StorageException (ddf.catalog.content.StorageException)12 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)12 AttributeImpl (ddf.catalog.data.impl.AttributeImpl)11 InputStream (java.io.InputStream)11 Map (java.util.Map)11 StorageProvider (ddf.catalog.content.StorageProvider)10 UpdateStorageResponse (ddf.catalog.content.operation.UpdateStorageResponse)10