Search in sources :

Example 16 with ContentItemImpl

use of ddf.catalog.content.data.impl.ContentItemImpl 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 17 with ContentItemImpl

use of ddf.catalog.content.data.impl.ContentItemImpl 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 18 with ContentItemImpl

use of ddf.catalog.content.data.impl.ContentItemImpl 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 19 with ContentItemImpl

use of ddf.catalog.content.data.impl.ContentItemImpl 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 20 with ContentItemImpl

use of ddf.catalog.content.data.impl.ContentItemImpl in project ddf by codice.

the class FileSystemStorageProviderTest method assertContentItemWithQualifier.

public CreateStorageResponse assertContentItemWithQualifier(String data, String mimeTypeRawData, String filename, String id, String qualifier, Map<String, Serializable> properties) throws Exception {
    // Simulates what ContentFrameworkImpl would do
    String uuid = StringUtils.defaultIfBlank(id, UUID.randomUUID().toString().replaceAll("-", ""));
    ByteSource byteSource = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return IOUtils.toInputStream(data);
        }
    };
    ContentItem contentItem = new ContentItemImpl(uuid, qualifier, byteSource, mimeTypeRawData, filename, byteSource.size(), mock(Metacard.class));
    CreateStorageRequest createRequest = new CreateStorageRequestImpl(Collections.singletonList(contentItem), properties);
    CreateStorageResponse createResponse = provider.create(createRequest);
    List<ContentItem> createdContentItems = createResponse.getCreatedContentItems();
    ContentItem createdContentItem = createdContentItems.isEmpty() ? null : createdContentItems.get(0);
    assertNotNull(createdContentItem);
    String createdId = createdContentItem.getId();
    assertNotNull(createdId);
    assertThat(createdId, equalTo(uuid));
    String contentUri = createdContentItem.getUri();
    LOGGER.debug("contentUri = {}", contentUri);
    assertNotNull(contentUri);
    String expectedContentUri = ContentItem.CONTENT_SCHEME + ":" + uuid + ((StringUtils.isNotBlank(qualifier)) ? "#" + qualifier : "");
    assertThat(contentUri, equalTo(expectedContentUri));
    assertTrue(createdContentItem.getSize() > 0);
    String createdMimeType = createdContentItem.getMimeTypeRawData().replace(";", "");
    List<String> createdMimeTypeArr = new ArrayList<>(Arrays.asList(createdMimeType.split(" ")));
    List<String> givenMimeTypeArr = new ArrayList<>(Arrays.asList(mimeTypeRawData.replace(";", "").split(" ")));
    assertEquals(createdMimeTypeArr.size(), givenMimeTypeArr.size());
    givenMimeTypeArr.removeAll(createdMimeTypeArr);
    assertThat(givenMimeTypeArr.size(), is(0));
    provider.commit(createRequest);
    return createResponse;
}
Also used : CreateStorageResponse(ddf.catalog.content.operation.CreateStorageResponse) Metacard(ddf.catalog.data.Metacard) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) ArrayList(java.util.ArrayList) ByteSource(com.google.common.io.ByteSource) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest)

Aggregations

ContentItemImpl (ddf.catalog.content.data.impl.ContentItemImpl)29 ContentItem (ddf.catalog.content.data.ContentItem)25 Metacard (ddf.catalog.data.Metacard)24 Test (org.junit.Test)17 ByteSource (com.google.common.io.ByteSource)14 CreateStorageRequestImpl (ddf.catalog.content.operation.impl.CreateStorageRequestImpl)14 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)12 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)10 IOException (java.io.IOException)8 InputStream (java.io.InputStream)8 Matchers.isEmptyString (org.hamcrest.Matchers.isEmptyString)8 CreateStorageResponse (ddf.catalog.content.operation.CreateStorageResponse)7 CreateResponse (ddf.catalog.operation.CreateResponse)7 UpdateStorageRequestImpl (ddf.catalog.content.operation.impl.UpdateStorageRequestImpl)6 Serializable (java.io.Serializable)6 URI (java.net.URI)6 CreateStorageRequest (ddf.catalog.content.operation.CreateStorageRequest)5 UpdateStorageRequest (ddf.catalog.content.operation.UpdateStorageRequest)5 AttributeImpl (ddf.catalog.data.impl.AttributeImpl)5