Search in sources :

Example 96 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project ddf by codice.

the class ConfigurationAdminExtTest method testListServicesInvalidSyntaxException.

/**
     * Tests the {@link ConfigurationAdminExt#listServices(String, String)} method
     * for the case where configurationAdmin.listConfigurations(....) throws an InvalidSyntaxException
     *
     * @throws Exception
     */
@Test
public void testListServicesInvalidSyntaxException() throws Exception {
    setUpListServices();
    setUpTestConfig();
    doThrow(new InvalidSyntaxException("", "")).when(testConfigAdmin).listConfigurations(anyString());
    List<Map<String, Object>> result = configurationAdminExt.listServices(TEST_FACT_FILTER, TEST_FILTER);
    assertThat("Should recover gracefully but not add to the given data.", (String) result.get(0).get("name"), is(TEST_OCD));
    assertThat("Should only contain one map.", result.size(), is(1));
}
Also used : InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 97 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project ddf by codice.

the class ConfigurationAdminExtTest method testGetConfigurationInvalidSyntaxException.

/**
     * Tests the {@link ConfigurationAdminExt#getConfiguration(String)} method
     * for the case where configurationAdmin.listConfigurations(..) throws an InvalidSyntaxException
     *
     * @throws Exception
     */
@Test
public void testGetConfigurationInvalidSyntaxException() throws Exception {
    doThrow(new InvalidSyntaxException("", "")).when(testConfigAdmin).listConfigurations(anyString());
    Configuration result = configurationAdminExt.getConfiguration(TEST_PID);
    assertThat("Should handle the exception gracefully and return null.", result, is(nullValue()));
}
Also used : Configuration(org.osgi.service.cm.Configuration) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Test(org.junit.Test)

Example 98 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project ddf by codice.

the class DumpCommand method executeWithSubject.

@Override
protected Object executeWithSubject() throws Exception {
    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;
    }
    SecurityLogger.audit("Called catalog:dump command with path : {}", dirPath);
    CatalogFacade catalog = getCatalog();
    if (StringUtils.isNotBlank(zipFileName)) {
        zipArgs = new HashMap<>();
        zipArgs.put(FILE_PATH, dirPath + zipFileName);
    }
    QueryImpl query = new QueryImpl(getFilter());
    query.setRequestsTotalResultsCount(false);
    query.setPageSize(pageSize);
    Map<String, Serializable> props = new HashMap<>();
    // Avoid caching all results while dumping with native query mode
    props.put("mode", "native");
    final AtomicLong resultCount = new AtomicLong(0);
    long start = System.currentTimeMillis();
    SourceResponse response = catalog.query(new QueryRequestImpl(query, props));
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(multithreaded);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    final ExecutorService executorService = new ThreadPoolExecutor(multithreaded, multithreaded, 0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);
    while (response.getResults().size() > 0) {
        response = catalog.query(new QueryRequestImpl(query, props));
        if (StringUtils.isNotBlank(zipFileName)) {
            try {
                Optional<QueryResponseTransformer> zipCompression = getZipCompression();
                if (zipCompression.isPresent()) {
                    BinaryContent binaryContent = zipCompression.get().transform(response, zipArgs);
                    if (binaryContent != null) {
                        IOUtils.closeQuietly(binaryContent.getInputStream());
                    }
                    Long resultSize = (long) response.getResults().size();
                    printStatus(resultCount.addAndGet(resultSize));
                }
            } catch (InvalidSyntaxException e) {
                LOGGER.info("No Zip Transformer found.  Unable export metacards to a zip file.");
            }
        } else if (multithreaded > 1) {
            final List<Result> results = new ArrayList<>(response.getResults());
            executorService.submit(() -> {
                boolean transformationFailed = false;
                for (final Result result : results) {
                    Metacard metacard = result.getMetacard();
                    try {
                        exportMetacard(dumpDir, metacard);
                    } catch (IOException | CatalogTransformerException e) {
                        transformationFailed = true;
                        LOGGER.debug("Failed to dump metacard {}", metacard.getId(), e);
                        executorService.shutdownNow();
                    }
                    printStatus(resultCount.incrementAndGet());
                }
                if (transformationFailed) {
                    LOGGER.info("One or more metacards failed to transform. Enable debug log for more details.");
                }
            });
        } else {
            for (final Result result : response.getResults()) {
                Metacard metacard = result.getMetacard();
                exportMetacard(dumpDir, metacard);
                printStatus(resultCount.incrementAndGet());
            }
        }
        if (response.getResults().size() < pageSize || pageSize == -1) {
            break;
        }
        if (pageSize > 0) {
            query.setStartIndex(query.getStartIndex() + pageSize);
        }
    }
    executorService.shutdown();
    while (!executorService.isTerminated()) {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
        // ignore
        }
    }
    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 : Serializable(java.io.Serializable) HashMap(java.util.HashMap) BinaryContent(ddf.catalog.data.BinaryContent) Result(ddf.catalog.data.Result) QueryImpl(ddf.catalog.operation.impl.QueryImpl) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ArrayList(java.util.ArrayList) List(java.util.List) SourceResponse(ddf.catalog.operation.SourceResponse) RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) Period(org.joda.time.Period) AtomicLong(java.util.concurrent.atomic.AtomicLong) Metacard(ddf.catalog.data.Metacard) QueryResponseTransformer(ddf.catalog.transform.QueryResponseTransformer) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) ExecutorService(java.util.concurrent.ExecutorService) AtomicLong(java.util.concurrent.atomic.AtomicLong) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) File(java.io.File)

Example 99 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project ddf by codice.

the class OpenSearchSource method getInputTransformer.

private InputTransformer getInputTransformer(InputStream inputStream) {
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
        while (xmlStreamReader.hasNext()) {
            int next = xmlStreamReader.next();
            if (next == XMLStreamConstants.START_ELEMENT) {
                String namespaceUri = xmlStreamReader.getNamespaceURI();
                InputTransformer transformerReference = lookupTransformerReference(namespaceUri);
                if (transformerReference != null) {
                    return transformerReference;
                }
            }
        }
    } catch (XMLStreamException | InvalidSyntaxException e) {
        LOGGER.debug("Failed to parse transformer namespace", e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
        } catch (XMLStreamException e) {
            LOGGER.debug("failed to close namespace reader", e);
        }
    }
    return null;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) InputTransformer(ddf.catalog.transform.InputTransformer)

Example 100 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project ddf by codice.

the class ConfigurationAdminExt method addMetaTypeNamesToMap.

public List<Map<String, Object>> addMetaTypeNamesToMap(final Map ocdCollection, final String filterSpec, final String type) {
    Filter filter = null;
    if (filterSpec != null) {
        try {
            filter = getBundleContext().createFilter(filterSpec);
        } catch (InvalidSyntaxException ignore) {
        // don't care
        }
    }
    List<Map<String, Object>> metatypeList = new ArrayList<Map<String, Object>>();
    Iterator ei = ocdCollection.entrySet().iterator();
    while (ei.hasNext()) {
        Entry ociEntry = (Entry) ei.next();
        final String pid = (String) ociEntry.getKey();
        final ObjectClassDefinition ocd = (ObjectClassDefinition) ociEntry.getValue();
        if (filter == null) {
            Map<String, Object> metatype = new HashMap<String, Object>();
            metatype.put(MAP_ENTRY_ID, pid);
            metatype.put(MAP_ENTRY_NAME, ocd.getName());
            AttributeDefinition[] defs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
            metatype.put(MAP_ENTRY_METATYPE, createMetatypeMap(defs));
            metatypeList.add(metatype);
        } else {
            final Dictionary props = new Hashtable();
            props.put(type, pid);
            if (filter.match(props)) {
                Map<String, Object> metatype = new HashMap<String, Object>();
                metatype.put(MAP_ENTRY_ID, pid);
                metatype.put(MAP_ENTRY_NAME, ocd.getName());
                AttributeDefinition[] defs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
                metatype.put(MAP_ENTRY_METATYPE, createMetatypeMap(defs));
                metatypeList.add(metatype);
            }
        }
    }
    return metatypeList;
}
Also used : Dictionary(java.util.Dictionary) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) AttributeDefinition(org.osgi.service.metatype.AttributeDefinition) Entry(java.util.Map.Entry) Filter(org.osgi.framework.Filter) Iterator(java.util.Iterator) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) HashMap(java.util.HashMap) Map(java.util.Map) ObjectClassDefinition(org.osgi.service.metatype.ObjectClassDefinition)

Aggregations

InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)105 ServiceReference (org.osgi.framework.ServiceReference)54 Filter (org.osgi.framework.Filter)26 ArrayList (java.util.ArrayList)22 IOException (java.io.IOException)20 BundleContext (org.osgi.framework.BundleContext)16 ServiceTracker (org.osgi.util.tracker.ServiceTracker)14 HashMap (java.util.HashMap)12 Configuration (org.osgi.service.cm.Configuration)12 Map (java.util.Map)10 Test (org.junit.Test)9 Dictionary (java.util.Dictionary)8 Hashtable (java.util.Hashtable)8 List (java.util.List)6 ConfigurationException (org.osgi.service.cm.ConfigurationException)6 Metacard (ddf.catalog.data.Metacard)4 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)4 CatalogFramework (ddf.catalog.CatalogFramework)3 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)3 InputTransformer (ddf.catalog.transform.InputTransformer)3