Search in sources :

Example 41 with Optional

use of com.google.common.base.Optional in project GeoGig by boundlessgeo.

the class Show method printFormatted.

public void printFormatted(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline();
                ansi.fg(Color.YELLOW).a("FEATURE TYPE ID:  ").reset().a(ft.getId().toString()).newline().newline();
                ansi.a("ATTRIBUTES  ").newline();
                ansi.a("----------  ").newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject)).call();
                console.println(s);
            }
        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset().a(Integer.toString(tree.numTrees()).toString()).newline();
            printFeatureType(ansi, ft, true);
            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset().newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor())).reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor())).reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED).a(estimateSince(geogig.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ").a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED).a(estimateSince(geogig.getPlatform(), commit.getCommitter().getTimestamp())).reset().a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException("Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }
}
Also used : ResolveFeatureType(org.locationtech.geogig.api.plumbing.ResolveFeatureType) ConsoleReader(jline.console.ConsoleReader) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) Optional(com.google.common.base.Optional) RevObject(org.locationtech.geogig.api.RevObject) Date(java.util.Date) InvalidParameterException(java.security.InvalidParameterException) RevFeature(org.locationtech.geogig.api.RevFeature) RevObjectParse(org.locationtech.geogig.api.plumbing.RevObjectParse) CatObject(org.locationtech.geogig.api.plumbing.CatObject) RevObject(org.locationtech.geogig.api.RevObject) Ansi(org.fusesource.jansi.Ansi) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) GeoGIG(org.locationtech.geogig.api.GeoGIG) RevTree(org.locationtech.geogig.api.RevTree) RevCommit(org.locationtech.geogig.api.RevCommit)

Example 42 with Optional

use of com.google.common.base.Optional in project GeoGig by boundlessgeo.

the class Show method printRaw.

private void printRaw(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.a(ref).newline();
                ansi.a(feature.getId().toString()).newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    PropertyDescriptor attrib = attribs.get(i);
                    ansi.a(attrib.getName()).newline();
                    PropertyType attrType = attrib.getType();
                    String typeName = FieldType.forBinding(attrType.getBinding()).name();
                    if (attrType instanceof GeometryType) {
                        GeometryType gt = (GeometryType) attrType;
                        CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
                        String crsText = CrsTextSerializer.serialize(crs);
                        ansi.a(typeName).a(" ").a(crsText).newline();
                    } else {
                        ansi.a(typeName).newline();
                    }
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject)).call();
                console.println(s);
            }
        } else {
            CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject)).call();
            console.println(s);
        }
    }
}
Also used : ConsoleReader(jline.console.ConsoleReader) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) Optional(com.google.common.base.Optional) RevObject(org.locationtech.geogig.api.RevObject) PropertyType(org.opengis.feature.type.PropertyType) GeometryType(org.opengis.feature.type.GeometryType) RevFeature(org.locationtech.geogig.api.RevFeature) RevObjectParse(org.locationtech.geogig.api.plumbing.RevObjectParse) CatObject(org.locationtech.geogig.api.plumbing.CatObject) RevObject(org.locationtech.geogig.api.RevObject) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Ansi(org.fusesource.jansi.Ansi) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) GeoGIG(org.locationtech.geogig.api.GeoGIG)

Example 43 with Optional

use of com.google.common.base.Optional in project GeoGig by boundlessgeo.

the class OSMExport method getFeatures.

private Iterator<EntityContainer> getFeatures(String ref) {
    Optional<ObjectId> id = geogig.command(RevParse.class).setRefSpec(ref).call();
    if (!id.isPresent()) {
        return Iterators.emptyIterator();
    }
    LsTreeOp op = geogig.command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES).setReference(ref);
    if (bbox != null) {
        final Envelope env;
        try {
            env = new Envelope(Double.parseDouble(bbox.get(0)), Double.parseDouble(bbox.get(2)), Double.parseDouble(bbox.get(1)), Double.parseDouble(bbox.get(3)));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Wrong bbox definition");
        }
        Predicate<Bounded> filter = new Predicate<Bounded>() {

            @Override
            public boolean apply(final Bounded bounded) {
                boolean intersects = bounded.intersects(env);
                return intersects;
            }
        };
        op.setBoundsFilter(filter);
    }
    Iterator<NodeRef> iterator = op.call();
    final EntityConverter converter = new EntityConverter();
    Function<NodeRef, EntityContainer> function = new Function<NodeRef, EntityContainer>() {

        @Override
        @Nullable
        public EntityContainer apply(@Nullable NodeRef ref) {
            RevFeature revFeature = geogig.command(RevObjectParse.class).setObjectId(ref.objectId()).call(RevFeature.class).get();
            SimpleFeatureType featureType;
            if (ref.path().startsWith(OSMUtils.NODE_TYPE_NAME)) {
                featureType = OSMUtils.nodeType();
            } else {
                featureType = OSMUtils.wayType();
            }
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
            RevFeatureType revFeatureType = RevFeatureTypeImpl.build(featureType);
            List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
            ImmutableList<Optional<Object>> values = revFeature.getValues();
            for (int i = 0; i < descriptors.size(); i++) {
                PropertyDescriptor descriptor = descriptors.get(i);
                Optional<Object> value = values.get(i);
                featureBuilder.set(descriptor.getName(), value.orNull());
            }
            SimpleFeature feature = featureBuilder.buildFeature(ref.name());
            Entity entity = converter.toEntity(feature, null);
            EntityContainer container;
            if (entity instanceof Node) {
                container = new NodeContainer((Node) entity);
            } else {
                container = new WayContainer((Way) entity);
            }
            return container;
        }
    };
    return Iterators.transform(iterator, function);
}
Also used : EntityConverter(org.locationtech.geogig.osm.internal.EntityConverter) Entity(org.openstreetmap.osmosis.core.domain.v0_6.Entity) WayContainer(org.openstreetmap.osmosis.core.container.v0_6.WayContainer) Node(org.openstreetmap.osmosis.core.domain.v0_6.Node) EntityContainer(org.openstreetmap.osmosis.core.container.v0_6.EntityContainer) NodeContainer(org.openstreetmap.osmosis.core.container.v0_6.NodeContainer) Envelope(com.vividsolutions.jts.geom.Envelope) Way(org.openstreetmap.osmosis.core.domain.v0_6.Way) Predicate(com.google.common.base.Predicate) NodeRef(org.locationtech.geogig.api.NodeRef) Function(com.google.common.base.Function) Bounded(org.locationtech.geogig.api.Bounded) RevFeature(org.locationtech.geogig.api.RevFeature) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) Optional(com.google.common.base.Optional) ObjectId(org.locationtech.geogig.api.ObjectId) SimpleFeature(org.opengis.feature.simple.SimpleFeature) LsTreeOp(org.locationtech.geogig.api.plumbing.LsTreeOp) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) RevObjectParse(org.locationtech.geogig.api.plumbing.RevObjectParse) Nullable(javax.annotation.Nullable) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Example 44 with Optional

use of com.google.common.base.Optional in project GeoGig by boundlessgeo.

the class OSMExportPG method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) {
    Preconditions.checkNotNull(mappingFile != null, "A data mapping file must be specified");
    final Mapping mapping = Mapping.fromFile(mappingFile);
    List<MappingRule> rules = mapping.getRules();
    checkParameter(!rules.isEmpty(), "No rules are defined in the specified mapping");
    for (final MappingRule rule : mapping.getRules()) {
        Function<Feature, Optional<Feature>> function = new Function<Feature, Optional<Feature>>() {

            @Override
            @Nullable
            public Optional<Feature> apply(@Nullable Feature feature) {
                Optional<Feature> mapped = rule.apply(feature);
                if (mapped.isPresent()) {
                    return Optional.of(mapped.get());
                }
                return Optional.absent();
            }
        };
        SimpleFeatureType outputFeatureType = rule.getFeatureType();
        String path = getOriginTreesFromOutputFeatureType(outputFeatureType);
        DataStore dataStore = null;
        try {
            dataStore = getDataStore();
            String tableName = outputFeatureType.getName().getLocalPart();
            if (Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
                if (!overwrite) {
                    throw new CommandFailedException("A table named '" + tableName + "'already exists. Use -o to overwrite");
                }
            } else {
                try {
                    dataStore.createSchema(outputFeatureType);
                } catch (IOException e) {
                    throw new CommandFailedException("Cannot create new table in database", e);
                }
            }
            final SimpleFeatureSource featureSource = dataStore.getFeatureSource(tableName);
            if (!(featureSource instanceof SimpleFeatureStore)) {
                throw new CommandFailedException("Could not create feature store. Data source is read only.");
            }
            final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
            if (overwrite) {
                featureStore.removeFeatures(Filter.INCLUDE);
            }
            ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFeatureTypeConversionFunction(function);
            try {
                op.setProgressListener(cli.getProgressListener()).call();
                cli.getConsole().println("OSM data exported successfully to " + tableName);
            } catch (IllegalArgumentException iae) {
                throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
            } catch (GeoToolsOpException e) {
                throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Cannot connect to database: " + e.getMessage(), e);
        } finally {
            if (dataStore != null) {
                dataStore.dispose();
            }
        }
    }
}
Also used : Optional(com.google.common.base.Optional) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) Mapping(org.locationtech.geogig.osm.internal.Mapping) IOException(java.io.IOException) MappingRule(org.locationtech.geogig.osm.internal.MappingRule) Feature(org.opengis.feature.Feature) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) Function(com.google.common.base.Function) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) DataStore(org.geotools.data.DataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) Nullable(javax.annotation.Nullable)

Example 45 with Optional

use of com.google.common.base.Optional in project GeoGig by boundlessgeo.

the class ImportOpTest method testAlter.

@Test
public void testAlter() throws Exception {
    ImportOp importOp = geogig.command(ImportOp.class);
    importOp.setDataStore(TestHelper.createTestFactory().createDataStore(null));
    importOp.setTable("table1");
    importOp.call();
    importOp.setTable("table2");
    importOp.setDestinationPath("table1");
    importOp.setAlter(true);
    importOp.call();
    Iterator<NodeRef> features = geogig.command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES).call();
    ArrayList<NodeRef> list = Lists.newArrayList(features);
    assertEquals(3, list.size());
    Optional<RevFeature> feature = geogig.command(RevObjectParse.class).setRefSpec("WORK_HEAD:table1/feature1").call(RevFeature.class);
    assertTrue(feature.isPresent());
    ImmutableList<Optional<Object>> values = feature.get().getValues();
    assertEquals(2, values.size());
    assertTrue(values.get(0).isPresent());
    assertFalse(values.get(1).isPresent());
    TreeSet<ObjectId> set = Sets.newTreeSet();
    for (NodeRef node : list) {
        set.add(node.getMetadataId());
    }
    assertEquals(1, set.size());
    Optional<RevFeatureType> featureType = geogig.command(RevObjectParse.class).setObjectId(set.iterator().next()).call(RevFeatureType.class);
    assertTrue(featureType.isPresent());
    assertEquals("table1", featureType.get().getName().getLocalPart());
    assertEquals("name", featureType.get().sortedDescriptors().get(1).getName().getLocalPart());
}
Also used : NodeRef(org.locationtech.geogig.api.NodeRef) Optional(com.google.common.base.Optional) ObjectId(org.locationtech.geogig.api.ObjectId) RevFeature(org.locationtech.geogig.api.RevFeature) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) Test(org.junit.Test)

Aggregations

Optional (com.google.common.base.Optional)319 List (java.util.List)79 Test (org.junit.Test)72 ArrayList (java.util.ArrayList)64 ReadFailedException (org.opendaylight.controller.md.sal.common.api.data.ReadFailedException)45 Map (java.util.Map)44 RevFeature (org.locationtech.geogig.api.RevFeature)42 Collections (java.util.Collections)38 InstanceIdentifier (org.opendaylight.yangtools.yang.binding.InstanceIdentifier)36 Logger (org.slf4j.Logger)36 LoggerFactory (org.slf4j.LoggerFactory)36 ExecutionException (java.util.concurrent.ExecutionException)35 LogicalDatastoreType (org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType)33 ImmutableList (com.google.common.collect.ImmutableList)32 HashMap (java.util.HashMap)32 DataBroker (org.opendaylight.controller.md.sal.binding.api.DataBroker)30 ReadOnlyTransaction (org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction)30 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)28 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)28 File (java.io.File)27