Search in sources :

Example 51 with ByteSource

use of com.google.common.io.ByteSource 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 52 with ByteSource

use of com.google.common.io.ByteSource 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 53 with ByteSource

use of com.google.common.io.ByteSource in project ddf by codice.

the class GeoNamesFileExtractor method unZipInputStream.

/**
     * Unzips a file and returns the output as a new InputStream
     *
     * @param resource    - the name of the resource file to be unzipped
     * @param inputStream - the InputStream for the file to be unzipped
     * @return - the unzipped file as an InputStream
     * @throws GeoEntryExtractionException when the given file fails to be unzipped.
     */
private InputStream unZipInputStream(String resource, InputStream inputStream) throws GeoEntryExtractionException {
    try (TemporaryFileBackedOutputStream bufferedOutputStream = new TemporaryFileBackedOutputStream(BUFFER_SIZE);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            // GeoNames <filename>.zip files will contain <filename>.txt and readme.txt
            if (!zipEntry.getName().equals("readme.txt")) {
                byte[] data = new byte[BUFFER_SIZE];
                int bytesRead;
                while ((bytesRead = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    bufferedOutputStream.write(data, 0, bytesRead);
                }
                ByteSource zipByteSource = bufferedOutputStream.asByteSource();
                bufferedOutputStream.flush();
                fileSize = zipByteSource.size();
                return zipByteSource.openBufferedStream();
            }
        }
    } catch (IOException e) {
        throw new GeoEntryExtractionException("Unable to unzip " + resource, e);
    }
    throw new GeoEntryExtractionException("Unable to unzip " + resource);
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) GeoEntryExtractionException(org.codice.ddf.spatial.geocoding.GeoEntryExtractionException) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) ZipEntry(java.util.zip.ZipEntry) ByteSource(com.google.common.io.ByteSource) IOException(java.io.IOException)

Example 54 with ByteSource

use of com.google.common.io.ByteSource in project ddf by codice.

the class GeoNamesFileExtractor method getInputStreamFromUrl.

/**
     * Download a GeoNames .zip file from a remote location
     *
     * @param resource         - the name of the zip file to download ( ex. AD )
     * @param response         - the response from the get request
     * @param inputStream      - the InputStream from the web connection
     * @param progressCallback -  the callback to receive updates about the progress, may be
     *                         null if you don't want any updates
     * @throws GeoNamesRemoteDownloadException when the connection could not be established or the
     *                                         file could not be downloaded.
     */
private InputStream getInputStreamFromUrl(String resource, Response response, InputStream inputStream, ProgressCallback progressCallback) throws GeoNamesRemoteDownloadException {
    int responseCode = 0;
    try (TemporaryFileBackedOutputStream fileOutputStream = new TemporaryFileBackedOutputStream(BUFFER_SIZE)) {
        responseCode = response.getStatus();
        int totalFileSize = response.getLength();
        if (inputStream == null) {
            throw new GeoNamesRemoteDownloadException("Unable to get input stream from " + url + ".  Server responded with : " + responseCode);
        }
        double totalBytesRead = 0.0;
        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            if (progressCallback != null) {
                progressCallback.updateProgress((int) ((totalBytesRead / totalFileSize) * 50));
            }
        }
        if (progressCallback != null) {
            progressCallback.updateProgress(50);
        }
        ByteSource byteSource = fileOutputStream.asByteSource();
        fileOutputStream.flush();
        inputStream.close();
        closeConnection();
        return byteSource.openBufferedStream();
    } catch (IOException e) {
        throw new GeoNamesRemoteDownloadException("Unable to download " + resource + " from " + url + ".  Server responded with : " + responseCode, e);
    }
}
Also used : GeoNamesRemoteDownloadException(org.codice.ddf.spatial.geocoding.GeoNamesRemoteDownloadException) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) ByteSource(com.google.common.io.ByteSource) IOException(java.io.IOException)

Example 55 with ByteSource

use of com.google.common.io.ByteSource 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

ByteSource (com.google.common.io.ByteSource)68 Test (org.junit.Test)33 IOException (java.io.IOException)30 InputStream (java.io.InputStream)22 ByteArrayInputStream (java.io.ByteArrayInputStream)18 Metacard (ddf.catalog.data.Metacard)15 ContentItem (ddf.catalog.content.data.ContentItem)14 ContentItemImpl (ddf.catalog.content.data.impl.ContentItemImpl)14 File (java.io.File)14 ArrayList (java.util.ArrayList)10 CreateStorageRequestImpl (ddf.catalog.content.operation.impl.CreateStorageRequestImpl)9 URI (java.net.URI)8 HashMap (java.util.HashMap)8 CreateStorageResponse (ddf.catalog.content.operation.CreateStorageResponse)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 Path (java.nio.file.Path)7 Matchers.isEmptyString (org.hamcrest.Matchers.isEmptyString)7 FileInputStream (java.io.FileInputStream)6 Serializable (java.io.Serializable)6 StringWriter (java.io.StringWriter)6