Search in sources :

Example 6 with CatalogFacade

use of org.codice.ddf.commands.catalog.facade.CatalogFacade in project ddf by codice.

the class MigrateCommand method executeWithSubject.

@Override
protected Object executeWithSubject() throws Exception {
    final List<CatalogProvider> providers = getCatalogProviders();
    if (listProviders) {
        if (providers.size() == 0) {
            console.println("There are no available Providers.");
            return null;
        }
        console.println("Available Providers:");
        providers.stream().map(p -> p.getClass().getSimpleName()).forEach(id -> console.println("\t" + id));
        return null;
    }
    if (batchSize > MAX_BATCH_SIZE || batchSize < 1) {
        console.println("Batch Size must be between 1 and " + MAX_BATCH_SIZE + ".");
        return null;
    }
    if (providers.isEmpty() || providers.size() < 2) {
        console.println("Not enough CatalogProviders installed to migrate.");
        return null;
    }
    final CatalogProvider fromProvider = promptForProvider("FROM", fromProviderId, providers);
    if (fromProvider == null) {
        console.println("Invalid \"FROM\" Provider id.");
        return null;
    }
    console.println("FROM Provider ID: " + fromProvider.getClass().getSimpleName());
    final CatalogProvider toProvider = promptForProvider("TO", toProviderId, providers);
    if (toProvider == null) {
        console.println("Invalid \"TO\" Provider id.");
        return null;
    }
    console.println("TO Provider ID: " + toProvider.getClass().getSimpleName());
    CatalogFacade queryProvider = new Provider(fromProvider);
    CatalogFacade ingestProvider = new Provider(toProvider);
    start = System.currentTimeMillis();
    console.println("Starting migration.");
    duplicateInBatches(queryProvider, ingestProvider, getFilter());
    console.println();
    long end = System.currentTimeMillis();
    String completed = String.format(" %d record(s) migrated; %d record(s) failed; completed in %3.3f seconds.", ingestedCount.get(), failedCount.get(), (end - start) / MS_PER_SECOND);
    LOGGER.debug("Migration Complete: {}", completed);
    console.println(completed);
    return null;
}
Also used : QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) StringUtils(org.apache.commons.lang.StringUtils) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) LoggerFactory(org.slf4j.LoggerFactory) ServiceComparator(ddf.catalog.util.impl.ServiceComparator) ArrayList(java.util.ArrayList) Command(org.apache.karaf.shell.api.action.Command) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) QueryRequest(ddf.catalog.operation.QueryRequest) SortByImpl(ddf.catalog.filter.impl.SortByImpl) SourceProcessingDetails(ddf.catalog.operation.SourceProcessingDetails) SortOrder(org.opengis.filter.sort.SortOrder) ServiceReference(org.osgi.framework.ServiceReference) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) IOException(java.io.IOException) FederationException(ddf.catalog.federation.FederationException) Collectors(java.util.stream.Collectors) Provider(org.codice.ddf.commands.catalog.facade.Provider) List(java.util.List) SourceResponse(ddf.catalog.operation.SourceResponse) TreeMap(java.util.TreeMap) CatalogProvider(ddf.catalog.source.CatalogProvider) Service(org.apache.karaf.shell.api.action.lifecycle.Service) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade) ServiceTracker(org.osgi.util.tracker.ServiceTracker) Filter(org.opengis.filter.Filter) Option(org.apache.karaf.shell.api.action.Option) CatalogProvider(ddf.catalog.source.CatalogProvider) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade) Provider(org.codice.ddf.commands.catalog.facade.Provider) CatalogProvider(ddf.catalog.source.CatalogProvider)

Example 7 with CatalogFacade

use of org.codice.ddf.commands.catalog.facade.CatalogFacade in project ddf by codice.

the class DumpCommand method executeWithSubject.

@Override
protected final Object executeWithSubject() throws Exception {
    if (signer == null) {
        signer = new DigitalSignature(security);
    }
    if (FilenameUtils.getExtension(dirPath).equals("") && !dirPath.endsWith(File.separator)) {
        dirPath += File.separator;
    }
    final File dumpDir = new File(dirPath);
    if (!dumpDir.exists()) {
        printErrorMessage("Directory [" + dirPath + "] must exist.");
        console.println("If the directory does indeed exist, try putting the path in quotes.");
        return null;
    }
    if (!dumpDir.isDirectory()) {
        printErrorMessage("Path [" + dirPath + "] must be a directory.");
        return null;
    }
    if (!SERIALIZED_OBJECT_ID.matches(transformerId)) {
        transformers = getTransformers();
        if (transformers == null) {
            console.println(transformerId + " is an invalid metacard transformer.");
            return null;
        }
    }
    if (StringUtils.isNotBlank(zipFileName) && new File(dirPath + zipFileName).exists()) {
        console.println("Cannot dump Catalog.  Zip file " + zipFileName + " already exists.");
        return null;
    }
    if (StringUtils.isNotBlank(zipFileName) && !zipFileName.endsWith(".zip")) {
        zipFileName = zipFileName + ".zip";
    }
    securityLogger.audit("Called catalog:dump command with path : {}", dirPath);
    CatalogFacade catalog = getCatalog();
    SortBy sort = new SortByImpl(Core.ID, SortOrder.ASCENDING);
    QueryImpl query = new QueryImpl(getFilter());
    query.setRequestsTotalResultsCount(true);
    query.setPageSize(pageSize);
    query.setSortBy(sort);
    final AtomicLong resultCount = new AtomicLong(0);
    long start = System.currentTimeMillis();
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(multithreaded);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    final ExecutorService executorService = new ThreadPoolExecutor(multithreaded, multithreaded, 0L, TimeUnit.MILLISECONDS, blockingQueue, StandardThreadFactoryBuilder.newThreadFactory("dumpCommandThread"), rejectedExecutionHandler);
    QueryRequest queryRequest = new QueryRequestImpl(query);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Hits for Search: {}", catalog.query(queryRequest).getHits());
    }
    if (StringUtils.isNotBlank(zipFileName)) {
        File outputFile = new File(dirPath + zipFileName);
        createZip(catalog, queryRequest, outputFile, resultCount);
        String alias = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SystemBaseUrl.EXTERNAL_HOST));
        String password = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword"));
        try (InputStream inputStream = new FileInputStream(outputFile)) {
            byte[] signature = signer.createDigitalSignature(inputStream, alias, password);
            if (signature != null) {
                String epoch = Long.toString(Instant.now().getEpochSecond());
                String signatureFilepath = String.format("%sdump_%s.sig", dirPath, epoch);
                FileUtils.writeByteArrayToFile(new File(signatureFilepath), signature);
            }
        }
    } else {
        ResultIterable.resultIterable(catalog::query, queryRequest).stream().map(Collections::singletonList).map(result -> new SourceResponseImpl(queryRequest, result)).forEach(response -> handleResult(response, executorService, dumpDir, resultCount));
    }
    executorService.shutdown();
    boolean interrupted = false;
    try {
        while (!executorService.isTerminated()) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                interrupted = true;
            }
        }
    } finally {
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
    }
    long end = System.currentTimeMillis();
    String elapsedTime = timeFormatter.print(new Period(start, end).withMillis(0));
    console.printf(" %d file(s) dumped in %s\t%n", resultCount.get(), elapsedTime);
    LOGGER.debug("{} file(s) dumped in {}", resultCount.get(), elapsedTime);
    console.println();
    securityLogger.audit("Exported {} files to {}", resultCount.get(), dirPath);
    return null;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) BinaryContent(ddf.catalog.data.BinaryContent) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) Command(org.apache.karaf.shell.api.action.Command) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) Map(java.util.Map) SortByImpl(ddf.catalog.filter.impl.SortByImpl) URI(java.net.URI) ZipEntry(java.util.zip.ZipEntry) ServiceReference(org.osgi.framework.ServiceReference) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) StandardThreadFactoryBuilder(org.codice.ddf.platform.util.StandardThreadFactoryBuilder) ResourceRequestById(ddf.catalog.operation.impl.ResourceRequestById) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) BlockingQueue(java.util.concurrent.BlockingQueue) PrivilegedAction(java.security.PrivilegedAction) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Serializable(java.io.Serializable) Objects(java.util.Objects) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) Attribute(ddf.catalog.data.Attribute) PeriodFormatterBuilder(org.joda.time.format.PeriodFormatterBuilder) AccessController(java.security.AccessController) FilenameUtils(org.apache.commons.io.FilenameUtils) FileBackedOutputStream(com.google.common.io.FileBackedOutputStream) ResourceResponse(ddf.catalog.operation.ResourceResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ZipOutputStream(java.util.zip.ZipOutputStream) ResultIterable(ddf.catalog.util.impl.ResultIterable) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) HashMap(java.util.HashMap) PeriodFormatter(org.joda.time.format.PeriodFormatter) Resource(ddf.catalog.resource.Resource) ArrayList(java.util.ArrayList) Reference(org.apache.karaf.shell.api.action.lifecycle.Reference) SortBy(org.opengis.filter.sort.SortBy) ContentItem(ddf.catalog.content.data.ContentItem) Constants(ddf.catalog.Constants) Metacard(ddf.catalog.data.Metacard) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ResourceRequest(ddf.catalog.operation.ResourceRequest) QueryRequest(ddf.catalog.operation.QueryRequest) ObjectOutputStream(java.io.ObjectOutputStream) Result(ddf.catalog.data.Result) SimpleEntry(java.util.AbstractMap.SimpleEntry) Core(ddf.catalog.data.types.Core) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) SortOrder(org.opengis.filter.sort.SortOrder) Period(org.joda.time.Period) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) SystemBaseUrl(org.codice.ddf.configuration.SystemBaseUrl) SecurityLogger(ddf.security.audit.SecurityLogger) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Argument(org.apache.karaf.shell.api.action.Argument) FileInputStream(java.io.FileInputStream) File(java.io.File) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) SourceResponse(ddf.catalog.operation.SourceResponse) 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) Collections(java.util.Collections) InputStream(java.io.InputStream) DigitalSignature(org.codice.ddf.commands.util.DigitalSignature) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) SortBy(org.opengis.filter.sort.SortBy) QueryImpl(ddf.catalog.operation.impl.QueryImpl) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade) Collections(java.util.Collections) QueryRequest(ddf.catalog.operation.QueryRequest) RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DigitalSignature(org.codice.ddf.commands.util.DigitalSignature) Period(org.joda.time.Period) FileInputStream(java.io.FileInputStream) AtomicLong(java.util.concurrent.atomic.AtomicLong) SortByImpl(ddf.catalog.filter.impl.SortByImpl) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ExecutorService(java.util.concurrent.ExecutorService) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) File(java.io.File)

Example 8 with CatalogFacade

use of org.codice.ddf.commands.catalog.facade.CatalogFacade in project ddf by codice.

the class DescribeCommand method executeWithSubject.

@Override
protected Object executeWithSubject() throws Exception {
    CatalogFacade catalog = getCatalog();
    console.printf(FORMAT_STR, "title", catalog.getTitle());
    console.printf(FORMAT_STR, "description", catalog.getDescription());
    console.printf(FORMAT_STR, "id", catalog.getId());
    console.printf(FORMAT_STR, "version", catalog.getVersion());
    return null;
}
Also used : CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade)

Aggregations

CatalogFacade (org.codice.ddf.commands.catalog.facade.CatalogFacade)8 Metacard (ddf.catalog.data.Metacard)5 QueryRequest (ddf.catalog.operation.QueryRequest)4 SourceResponse (ddf.catalog.operation.SourceResponse)4 QueryImpl (ddf.catalog.operation.impl.QueryImpl)4 QueryRequestImpl (ddf.catalog.operation.impl.QueryRequestImpl)4 Result (ddf.catalog.data.Result)3 SortByImpl (ddf.catalog.filter.impl.SortByImpl)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)2 IngestException (ddf.catalog.source.IngestException)2 SourceUnavailableException (ddf.catalog.source.SourceUnavailableException)2 UnsupportedQueryException (ddf.catalog.source.UnsupportedQueryException)2 File (java.io.File)2 Map (java.util.Map)2 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)2 ExecutorService (java.util.concurrent.ExecutorService)2 RejectedExecutionHandler (java.util.concurrent.RejectedExecutionHandler)2