Search in sources :

Example 31 with DataStoreException

use of org.apache.sis.storage.DataStoreException in project sis by apache.

the class Store method close.

/**
 * Closes this data store and releases any underlying resources.
 *
 * @throws DataStoreException if an error occurred while closing this data store.
 */
@Override
public synchronized void close() throws DataStoreException {
    final BufferedReader s = source;
    // Cleared first in case of failure.
    source = null;
    if (s != null)
        try {
            s.close();
        } catch (IOException e) {
            throw new DataStoreException(e);
        }
}
Also used : DataStoreException(org.apache.sis.storage.DataStoreException) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 32 with DataStoreException

use of org.apache.sis.storage.DataStoreException in project sis by apache.

the class WritableStore method add.

/**
 * Create a new file for the given resource.
 * This implementation uses the provider specified at creation time.
 */
@Override
public synchronized Resource add(final Resource resource) throws DataStoreException {
    ArgumentChecks.ensureNonNull("resource", resource);
    if (!(resource instanceof FeatureSet)) {
        throw new DataStoreException(message(Resources.Keys.CanNotStoreResourceType_2, new Object[] { StoreProvider.NAME, StoreUtilities.getInterface(resource.getClass()) }));
    }
    /*
         * If we determined in a previous method invocation that the given provider can not write feature set,
         * we are better to fail now instead of polluting the directory with files that we can not use.
         */
    if (isReadOnly) {
        throw new ReadOnlyStorageException(messages().getString(Resources.Keys.StoreIsReadOnly));
    }
    /*
         * Infer a filename from the resource identifier, if one can be found.
         * A suffix is added to the filename if available (some formats may have no suffix at all).
         *
         * TODO: find a more specific metadata property for this informtion.
         */
    final GenericName identifier = resource.getIdentifier().orElse(null);
    if (identifier == null) {
        throw new DataStoreException(message(Resources.Keys.MissingResourceIdentifier_1, StoreUtilities.getLabel(resource)));
    }
    String filename = identifier.toString();
    final String[] suffixes = StoreUtilities.getFileSuffixes(componentProvider.getClass());
    if (suffixes.length != 0) {
        filename += '.' + suffixes[0];
    }
    /*
         * Create new store/resource for write access, provided that no store already exist for the path.
         * We use the CREATE_NEW option in order to intentionally fail if the resource already exists.
         */
    final Path path = location.resolve(filename);
    if (!children.containsKey(path)) {
        final StorageConnector connector = new StorageConnector(path);
        connector.setOption(OptionKey.LOCALE, locale);
        connector.setOption(OptionKey.TIMEZONE, timezone);
        connector.setOption(OptionKey.ENCODING, encoding);
        connector.setOption(OptionKey.OPEN_OPTIONS, new StandardOpenOption[] { StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE });
        final DataStore store = componentProvider.open(connector);
        if (children.putIfAbsent(path, store) == null) {
            // TODO: handle transactional case.
            if (store instanceof WritableFeatureSet) {
                StoreUtilities.copy((FeatureSet) resource, (WritableFeatureSet) store);
                // Clear cache. TODO: we should do something more efficient.
                components = null;
                return store;
            }
            /*
                 * If the data store is not a WritableFeatureSet, current implementation can not use it.
                 * Files created by this failed attempt may remain; instead of trying to delete them with
                 * uncertain consequences, we set a flag for avoiding to pollute further the directory.
                 */
            isReadOnly = true;
            children.remove(path, store);
            final String name = store.getDisplayName();
            store.close();
            throw new DataStoreException(message(Resources.Keys.NotAWritableFeatureSet_1, name));
        }
        store.close();
    }
    throw new DataStoreException(message(Resources.Keys.ResourceAlreadyExists_1, path));
}
Also used : Path(java.nio.file.Path) StorageConnector(org.apache.sis.storage.StorageConnector) WritableFeatureSet(org.apache.sis.storage.WritableFeatureSet) DataStoreException(org.apache.sis.storage.DataStoreException) GenericName(org.opengis.util.GenericName) ReadOnlyStorageException(org.apache.sis.storage.ReadOnlyStorageException) DataStore(org.apache.sis.storage.DataStore) FeatureSet(org.apache.sis.storage.FeatureSet) WritableFeatureSet(org.apache.sis.storage.WritableFeatureSet)

Example 33 with DataStoreException

use of org.apache.sis.storage.DataStoreException in project sis by apache.

the class SQLStore method getMetadata.

/**
 * Returns information about the dataset as a whole. The returned metadata object can contain information
 * such as the list of feature types.
 *
 * @return information about the dataset.
 * @throws DataStoreException if an error occurred while reading the data.
 */
@Override
public synchronized Metadata getMetadata() throws DataStoreException {
    if (metadata == null) {
        final MetadataBuilder builder = new MetadataBuilder();
        builder.addSpatialRepresentation(SpatialRepresentationType.TEXT_TABLE);
        try (Connection c = source.getConnection()) {
            final Database<?> model = model(c);
            if (model.hasGeometry()) {
                builder.addSpatialRepresentation(SpatialRepresentationType.VECTOR);
            }
            if (model.hasRaster()) {
                builder.addSpatialRepresentation(SpatialRepresentationType.GRID);
            }
            model.listTables(c.getMetaData(), builder);
        } catch (DataStoreException e) {
            throw e;
        } catch (Exception e) {
            throw new DataStoreException(Exceptions.unwrap(e));
        }
        /*
             * Try to find a title from the data source description.
             */
        for (final String c : NAME_GETTERS) {
            try {
                final Method method = source.getClass().getMethod(c);
                if (method.getReturnType() == String.class) {
                    final String name = Strings.trimOrNull((String) method.invoke(source));
                    if (name != null) {
                        builder.addTitle(name);
                        break;
                    }
                }
            } catch (NoSuchMethodException | SecurityException e) {
            // Ignore - try the next method.
            } catch (ReflectiveOperationException e) {
                throw new DataStoreException(Exceptions.unwrap(e));
            }
        }
        metadata = builder.build(true);
    }
    return metadata;
}
Also used : DataStoreException(org.apache.sis.storage.DataStoreException) MetadataBuilder(org.apache.sis.internal.storage.MetadataBuilder) Connection(java.sql.Connection) Method(java.lang.reflect.Method) IllegalNameException(org.apache.sis.storage.IllegalNameException) DataStoreException(org.apache.sis.storage.DataStoreException)

Example 34 with DataStoreException

use of org.apache.sis.storage.DataStoreException in project sis by apache.

the class ConcatenatedFeatureSetTest method testCommonSuperType.

/**
 * Tests the concatenation of two feature sets having different feature types.
 *
 * @throws DataStoreException if an error occurred while concatenating the feature sets.
 */
@Test
@DependsOnMethod("testSameType")
public void testCommonSuperType() throws DataStoreException {
    /*
         * First, we prepare two types sharing a common ancestor. We'll create two types using same properties,
         * so we can ensure that all data is exposed upon traversal, not only data defined in the super type.
         */
    final FeatureTypeBuilder builder = new FeatureTypeBuilder();
    builder.addAttribute(Integer.class).setName("value");
    builder.setName("parent");
    final DefaultFeatureType superType = builder.build();
    builder.clear();
    builder.setSuperTypes(superType);
    builder.addAttribute(String.class).setName("label");
    final DefaultFeatureType t1 = builder.setName("t1").build();
    final DefaultFeatureType t2 = builder.setName("t2").build();
    // Populate a feature set for first type.
    final AbstractFeature t1f1 = t1.newInstance();
    t1f1.setPropertyValue("value", 2);
    t1f1.setPropertyValue("label", "first-first");
    final AbstractFeature t1f2 = t1.newInstance();
    t1f2.setPropertyValue("value", 3);
    t1f2.setPropertyValue("label", "first-second");
    final FeatureSet t1fs = new MemoryFeatureSet(null, t1, Arrays.asList(t1f1, t1f2));
    // Populate a feature set for second type.
    final AbstractFeature t2f1 = t2.newInstance();
    t2f1.setPropertyValue("value", 3);
    t2f1.setPropertyValue("label", "second-first");
    final AbstractFeature t2f2 = t2.newInstance();
    t2f2.setPropertyValue("value", 4);
    t2f2.setPropertyValue("label", "second-second");
    final FeatureSet t2fs = new MemoryFeatureSet(null, t2, Arrays.asList(t2f1, t2f2));
    /*
         * First, we'll test that total sum of value property is coherent with initialized features.
         * After that, we will ensure that we can get back the right labels for each subtype.
         */
    final FeatureSet set = ConcatenatedFeatureSet.create(t1fs, t2fs);
    final int sum = set.features(true).mapToInt(f -> (int) f.getPropertyValue("value")).sum();
    assertEquals("Sum of feature `value` property", 12, sum);
    final Object[] t1labels = set.features(false).filter(f -> t1.equals(f.getType())).map(f -> f.getPropertyValue("label")).toArray();
    assertArrayEquals("First type labels", new String[] { "first-first", "first-second" }, t1labels);
    final Object[] t2labels = set.features(false).filter(f -> t2.equals(f.getType())).map(f -> f.getPropertyValue("label")).toArray();
    assertArrayEquals("First type labels", new String[] { "second-first", "second-second" }, t2labels);
}
Also used : Arrays(java.util.Arrays) MetadataAssert(org.apache.sis.test.MetadataAssert) FeatureTypeBuilder(org.apache.sis.feature.builder.FeatureTypeBuilder) DefaultMetadata(org.apache.sis.metadata.iso.DefaultMetadata) Metadata(org.opengis.metadata.Metadata) FeatureCatalogueDescription(org.opengis.metadata.content.FeatureCatalogueDescription) Lineage(org.opengis.metadata.lineage.Lineage) Test(org.junit.Test) TestUtilities.getSingleton(org.apache.sis.test.TestUtilities.getSingleton) DefaultFeatureType(org.apache.sis.feature.DefaultFeatureType) DataStoreContentException(org.apache.sis.storage.DataStoreContentException) FeatureSet(org.apache.sis.storage.FeatureSet) DependsOnMethod(org.apache.sis.test.DependsOnMethod) TestCase(org.apache.sis.test.TestCase) DataStoreException(org.apache.sis.storage.DataStoreException) AbstractFeature(org.apache.sis.feature.AbstractFeature) Collections(java.util.Collections) FeatureTypeBuilder(org.apache.sis.feature.builder.FeatureTypeBuilder) DefaultFeatureType(org.apache.sis.feature.DefaultFeatureType) AbstractFeature(org.apache.sis.feature.AbstractFeature) FeatureSet(org.apache.sis.storage.FeatureSet) Test(org.junit.Test) DependsOnMethod(org.apache.sis.test.DependsOnMethod)

Example 35 with DataStoreException

use of org.apache.sis.storage.DataStoreException in project sis by apache.

the class ConcatenatedFeatureSetTest method noCommonType.

/**
 * Tests the concatenation of two feature sets having no common parent.
 * Creation of {@link ConcatenatedFeatureSet} is expected to fail.
 */
@Test
@DependsOnMethod("testCommonSuperType")
public void noCommonType() {
    final FeatureTypeBuilder builder = new FeatureTypeBuilder();
    builder.setName("super");
    final DefaultFeatureType mockSuperType = builder.build();
    final DefaultFeatureType firstType = builder.setSuperTypes(mockSuperType).setName("first").build();
    final DefaultFeatureType secondType = builder.clear().setName("second").build();
    final FeatureSet fs1 = new MemoryFeatureSet(null, firstType, Collections.emptyList());
    final FeatureSet fs2 = new MemoryFeatureSet(null, secondType, Collections.emptyList());
    try {
        FeatureSet concatenation = ConcatenatedFeatureSet.create(fs1, fs2);
        fail("Concatenation succeeded despite the lack of common type. Result is:\n" + concatenation);
    } catch (DataStoreContentException e) {
    // Expected behavior.
    } catch (DataStoreException e) {
        fail("Concatenation failed with an error reserved for other kind of error.");
    }
}
Also used : FeatureTypeBuilder(org.apache.sis.feature.builder.FeatureTypeBuilder) DataStoreException(org.apache.sis.storage.DataStoreException) DataStoreContentException(org.apache.sis.storage.DataStoreContentException) DefaultFeatureType(org.apache.sis.feature.DefaultFeatureType) FeatureSet(org.apache.sis.storage.FeatureSet) Test(org.junit.Test) DependsOnMethod(org.apache.sis.test.DependsOnMethod)

Aggregations

DataStoreException (org.apache.sis.storage.DataStoreException)39 IOException (java.io.IOException)16 DataStore (org.apache.sis.storage.DataStore)8 Path (java.nio.file.Path)6 DataStoreContentException (org.apache.sis.storage.DataStoreContentException)5 FeatureSet (org.apache.sis.storage.FeatureSet)5 GridCoverageResource (org.apache.sis.storage.GridCoverageResource)4 IllegalNameException (org.apache.sis.storage.IllegalNameException)4 Resource (org.apache.sis.storage.Resource)4 BackingStoreException (org.apache.sis.util.collection.BackingStoreException)4 FactoryException (org.opengis.util.FactoryException)4 Reader (java.io.Reader)3 UncheckedIOException (java.io.UncheckedIOException)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 URISyntaxException (java.net.URISyntaxException)3 ByteBuffer (java.nio.ByteBuffer)3 ProbeResult (org.apache.sis.storage.ProbeResult)3 BufferedReader (java.io.BufferedReader)2 Closeable (java.io.Closeable)2 File (java.io.File)2