Search in sources :

Example 71 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class ExceptionsTest method testCatalogTransformerException.

@Test
public void testCatalogTransformerException() {
    CatalogTransformerException cte = new CatalogTransformerException();
    assertNotNull(cte);
    cte = new CatalogTransformerException(msg);
    assertEquals(cte.getMessage(), msg);
    cte = new CatalogTransformerException(testCause);
    assertEquals(cte.getCause(), testCause);
    cte = new CatalogTransformerException(msg, testCause);
    assertEquals(cte.getMessage(), msg);
    assertEquals(cte.getCause(), testCause);
}
Also used : CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Test(org.junit.Test)

Example 72 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class ImportCommand method executeWithSubject.

@Override
protected final Object executeWithSubject() throws Exception {
    int metacards = 0;
    int content = 0;
    int derivedContent = 0;
    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) {
            String input = session.readLine("This will import data with no check to see if data is modified/corrupt. Do you wish to continue? (y/N) ", null);
            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 (StringUtils.isBlank(signatureFile)) {
            String message = "A signature file must be provided with import data";
            console.println(message);
            throw new CatalogCommandRuntimeException(message);
        }
        String alias = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty("org.codice.ddf.system.hostname"));
        try (FileInputStream fileIs = new FileInputStream(file);
            FileInputStream sigFileIs = new FileInputStream(signatureFile)) {
            if (verifier == null) {
                verifier = new DigitalSignature(security);
            }
            if (!verifier.verifyDigitalSignature(fileIs, sigFileIs, alias)) {
                throw new CatalogCommandRuntimeException("The provided data could not be verified");
            }
        }
    }
    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":
                    {
                        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: {}", LogSanitizer.sanitize(id));
                            entry = zipInputStream.getNextEntry();
                            continue;
                        }
                        metacard = applyInjectors(metacard, attributeInjectors);
                        catalogProvider.create(new CreateRequestImpl(metacard));
                        metacards++;
                        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 {}", LogSanitizer.sanitize(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) DigitalSignature(org.codice.ddf.commands.util.DigitalSignature) 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) ContentItem(ddf.catalog.content.data.ContentItem) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl)

Example 73 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class OpenSearchSource method doQueryById.

private SourceResponse doQueryById(QueryRequest queryRequest, WebClient restWebClient) throws UnsupportedQueryException {
    InputStream responseStream = performRequest(restWebClient);
    try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
        IOUtils.copyLarge(responseStream, fileBackedOutputStream);
        InputTransformer inputTransformer;
        try (InputStream inputStream = fileBackedOutputStream.asByteSource().openStream()) {
            inputTransformer = getInputTransformer(inputStream);
        }
        try (InputStream inputStream = fileBackedOutputStream.asByteSource().openStream()) {
            final Metacard metacard = inputTransformer.transform(inputStream);
            metacard.setSourceId(getId());
            ResultImpl result = new ResultImpl(metacard);
            List<Result> resultQueue = new ArrayList<>();
            resultQueue.add(result);
            return new SourceResponseImpl(queryRequest, resultQueue);
        }
    } catch (IOException | CatalogTransformerException e) {
        throw new UnsupportedQueryException("Problem with transformation.", e);
    }
}
Also used : TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) ArrayList(java.util.ArrayList) ResultImpl(ddf.catalog.data.impl.ResultImpl) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) InputTransformer(ddf.catalog.transform.InputTransformer) Result(ddf.catalog.data.Result) Metacard(ddf.catalog.data.Metacard)

Example 74 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class KMLTransformerImpl method transform.

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException {
    try {
        Placemark placemark = transformEntry(null, metacard, arguments);
        if (placemark.getStyleSelector().isEmpty() && StringUtils.isBlank(placemark.getStyleUrl())) {
            placemark.getStyleSelector().addAll(defaultStyle);
        }
        Kml kml = KmlFactory.createKml().withFeature(placemark);
        String transformedKmlString = kmlMarshaller.marshal(kml);
        InputStream kmlInputStream = new ByteArrayInputStream(transformedKmlString.getBytes(StandardCharsets.UTF_8));
        return new BinaryContentImpl(kmlInputStream, KML_MIMETYPE);
    } catch (Exception e) {
        LOGGER.debug("Error transforming metacard ({}) to KML: {}", metacard.getId(), e.getMessage());
        throw new CatalogTransformerException("Error transforming metacard to KML.", e);
    }
}
Also used : Placemark(de.micromata.opengis.kml.v_2_2_0.Placemark) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Kml(de.micromata.opengis.kml.v_2_2_0.Kml) KmlTransformations.encloseKml(org.codice.ddf.spatial.kml.util.KmlTransformations.encloseKml) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) MimeTypeParseException(javax.activation.MimeTypeParseException) IOException(java.io.IOException)

Example 75 with CatalogTransformerException

use of ddf.catalog.transform.CatalogTransformerException in project ddf by codice.

the class KMLTransformerImpl method transform.

@Override
public BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    LOGGER.trace("ENTERING: ResponseQueue transform");
    if (arguments == null) {
        LOGGER.debug("Null arguments, unable to complete transform");
        throw new CatalogTransformerException("Unable to complete transform without arguments");
    }
    String docId = UUID.randomUUID().toString();
    String restUriAbsolutePath = (String) arguments.get("url");
    LOGGER.debug("rest string url arg: {}", LogSanitizer.sanitize(restUriAbsolutePath));
    // Transform Metacards to KML
    Document kmlDoc = KmlFactory.createDocument();
    boolean needDefaultStyle = false;
    for (Result result : upstreamResponse.getResults()) {
        try {
            Placemark placemark = transformEntry(null, result.getMetacard(), arguments);
            if (placemark.getStyleSelector().isEmpty() && StringUtils.isEmpty(placemark.getStyleUrl())) {
                placemark.setStyleUrl("#default");
                needDefaultStyle = true;
            }
            kmlDoc.getFeature().add(placemark);
        } catch (CatalogTransformerException e) {
            LOGGER.debug("Error transforming current metacard ({}) to KML and will continue with remaining query responses.", LogSanitizer.sanitize(result.getMetacard().getId()), e);
        }
    }
    if (needDefaultStyle) {
        kmlDoc.getStyleSelector().addAll(defaultStyle);
    }
    Kml kmlResult = encloseKml(kmlDoc, docId, KML_RESPONSE_QUEUE_PREFIX + kmlDoc.getFeature().size() + CLOSE_PARENTHESIS);
    String transformedKml = kmlMarshaller.marshal(kmlResult);
    InputStream kmlInputStream = new ByteArrayInputStream(transformedKml.getBytes(StandardCharsets.UTF_8));
    LOGGER.trace("EXITING: ResponseQueue transform");
    return new BinaryContentImpl(kmlInputStream, KML_MIMETYPE);
}
Also used : Placemark(de.micromata.opengis.kml.v_2_2_0.Placemark) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Kml(de.micromata.opengis.kml.v_2_2_0.Kml) KmlTransformations.encloseKml(org.codice.ddf.spatial.kml.util.KmlTransformations.encloseKml) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) Document(de.micromata.opengis.kml.v_2_2_0.Document) Result(ddf.catalog.data.Result)

Aggregations

CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)112 IOException (java.io.IOException)53 Metacard (ddf.catalog.data.Metacard)44 InputStream (java.io.InputStream)40 ByteArrayInputStream (java.io.ByteArrayInputStream)29 BinaryContent (ddf.catalog.data.BinaryContent)25 InputTransformer (ddf.catalog.transform.InputTransformer)21 Serializable (java.io.Serializable)21 HashMap (java.util.HashMap)21 Result (ddf.catalog.data.Result)16 BinaryContentImpl (ddf.catalog.data.impl.BinaryContentImpl)15 TemporaryFileBackedOutputStream (org.codice.ddf.platform.util.TemporaryFileBackedOutputStream)14 ArrayList (java.util.ArrayList)13 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)12 Test (org.junit.Test)12 AttributeImpl (ddf.catalog.data.impl.AttributeImpl)10 MimeType (javax.activation.MimeType)10 SourceResponse (ddf.catalog.operation.SourceResponse)9 MetacardTransformer (ddf.catalog.transform.MetacardTransformer)8 List (java.util.List)8