Search in sources :

Example 1 with CommandFailedException

use of org.locationtech.geogig.cli.CommandFailedException in project GeoGig by boundlessgeo.

the class DiffTree method runInternal.

/**
     * Executes the diff-tree command with the specified options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (refSpec.size() > 2) {
        throw new CommandFailedException("Tree refspecs list is too long :" + refSpec);
    }
    if (treeStats && describe) {
        throw new CommandFailedException("Cannot use --describe and --tree-stats simultaneously");
    }
    GeoGIG geogig = cli.getGeogig();
    org.locationtech.geogig.api.plumbing.DiffTree diff = geogig.command(org.locationtech.geogig.api.plumbing.DiffTree.class);
    String oldVersion = resolveOldVersion();
    String newVersion = resolveNewVersion();
    diff.setOldVersion(oldVersion).setNewVersion(newVersion);
    Iterator<DiffEntry> diffEntries;
    if (paths.isEmpty()) {
        diffEntries = diff.setProgressListener(cli.getProgressListener()).call();
    } else {
        diffEntries = Iterators.emptyIterator();
        for (String path : paths) {
            Iterator<DiffEntry> moreEntries = diff.setPathFilter(path).setProgressListener(cli.getProgressListener()).call();
            diffEntries = Iterators.concat(diffEntries, moreEntries);
        }
    }
    DiffEntry diffEntry;
    HashMap<String, Long[]> stats = Maps.newHashMap();
    while (diffEntries.hasNext()) {
        diffEntry = diffEntries.next();
        StringBuilder sb = new StringBuilder();
        String path = diffEntry.newPath() != null ? diffEntry.newPath() : diffEntry.oldPath();
        if (describe) {
            sb.append(diffEntry.changeType().toString().charAt(0)).append(' ').append(path).append(LINE_BREAK);
            if (diffEntry.changeType() == ChangeType.MODIFIED) {
                FeatureDiff featureDiff = geogig.command(DiffFeature.class).setNewVersion(Suppliers.ofInstance(diffEntry.getNewObject())).setOldVersion(Suppliers.ofInstance(diffEntry.getOldObject())).call();
                Map<PropertyDescriptor, AttributeDiff> diffs = featureDiff.getDiffs();
                HashSet<PropertyDescriptor> diffDescriptors = Sets.newHashSet(diffs.keySet());
                NodeRef noderef = diffEntry.changeType() != ChangeType.REMOVED ? diffEntry.getNewObject() : diffEntry.getOldObject();
                RevFeatureType featureType = geogig.command(RevObjectParse.class).setObjectId(noderef.getMetadataId()).call(RevFeatureType.class).get();
                Optional<RevObject> obj = geogig.command(RevObjectParse.class).setObjectId(noderef.objectId()).call();
                RevFeature feature = (RevFeature) obj.get();
                ImmutableList<Optional<Object>> values = feature.getValues();
                ImmutableList<PropertyDescriptor> descriptors = featureType.sortedDescriptors();
                int idx = 0;
                for (PropertyDescriptor descriptor : descriptors) {
                    if (diffs.containsKey(descriptor)) {
                        AttributeDiff ad = diffs.get(descriptor);
                        sb.append(ad.getType().toString().charAt(0) + " " + descriptor.getName().toString() + LINE_BREAK);
                        if (!ad.getType().equals(TYPE.ADDED)) {
                            Object value = ad.getOldValue().orNull();
                            sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                            sb.append(LINE_BREAK);
                        }
                        if (!ad.getType().equals(TYPE.REMOVED)) {
                            Object value = ad.getNewValue().orNull();
                            sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                            sb.append(LINE_BREAK);
                        }
                        diffDescriptors.remove(descriptor);
                    } else {
                        sb.append("U ").append(descriptor.getName().toString()).append(LINE_BREAK);
                        sb.append(TextValueSerializer.asString(values.get(idx))).append(LINE_BREAK);
                    }
                    idx++;
                }
                for (PropertyDescriptor descriptor : diffDescriptors) {
                    AttributeDiff ad = diffs.get(descriptor);
                    sb.append(ad.getType().toString().charAt(0) + " " + descriptor.getName().toString() + LINE_BREAK);
                    if (!ad.getType().equals(TYPE.ADDED)) {
                        Object value = ad.getOldValue().orNull();
                        sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                        sb.append(LINE_BREAK);
                    }
                    if (!ad.getType().equals(TYPE.REMOVED)) {
                        Object value = ad.getNewValue().orNull();
                        sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                        sb.append(LINE_BREAK);
                    }
                }
            } else {
                NodeRef noderef = diffEntry.changeType() == ChangeType.ADDED ? diffEntry.getNewObject() : diffEntry.getOldObject();
                RevFeatureType featureType = geogig.command(RevObjectParse.class).setObjectId(noderef.getMetadataId()).call(RevFeatureType.class).get();
                Optional<RevObject> obj = geogig.command(RevObjectParse.class).setObjectId(noderef.objectId()).call();
                RevFeature feature = (RevFeature) obj.get();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    sb.append(diffEntry.changeType().toString().charAt(0));
                    sb.append(' ');
                    sb.append(featureType.sortedDescriptors().get(i).getName().toString());
                    sb.append(LINE_BREAK);
                    sb.append(TextValueSerializer.asString(value));
                    sb.append(LINE_BREAK);
                    i++;
                }
                sb.append(LINE_BREAK);
            }
            sb.append(LINE_BREAK);
            cli.getConsole().println(sb.toString());
        } else if (treeStats) {
            String parent = NodeRef.parentPath(path);
            if (!stats.containsKey(parent)) {
                stats.put(parent, new Long[] { 0l, 0l, 0l });
            }
            Long[] counts = stats.get(parent);
            if (diffEntry.changeType() == ChangeType.ADDED) {
                counts[0]++;
            } else if (diffEntry.changeType() == ChangeType.REMOVED) {
                counts[1]++;
            } else if (diffEntry.changeType() == ChangeType.MODIFIED) {
                counts[2]++;
            }
        } else {
            sb.append(path).append(' ');
            sb.append(diffEntry.oldObjectId().toString());
            sb.append(' ');
            sb.append(diffEntry.newObjectId().toString());
            cli.getConsole().println(sb.toString());
        }
    }
    if (treeStats) {
        for (String path : stats.keySet()) {
            StringBuffer sb = new StringBuffer();
            sb.append(path);
            Long[] counts = stats.get(path);
            for (int i = 0; i < counts.length; i++) {
                sb.append(" " + counts[i].toString());
            }
            cli.getConsole().println(sb.toString());
        }
    }
}
Also used : CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) FeatureDiff(org.locationtech.geogig.api.plumbing.diff.FeatureDiff) NodeRef(org.locationtech.geogig.api.NodeRef) RevFeature(org.locationtech.geogig.api.RevFeature) AttributeDiff(org.locationtech.geogig.api.plumbing.diff.AttributeDiff) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) DiffEntry(org.locationtech.geogig.api.plumbing.diff.DiffEntry) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) Optional(com.google.common.base.Optional) RevObject(org.locationtech.geogig.api.RevObject) DiffFeature(org.locationtech.geogig.api.plumbing.DiffFeature) RevObjectParse(org.locationtech.geogig.api.plumbing.RevObjectParse) RevObject(org.locationtech.geogig.api.RevObject) GeoGIG(org.locationtech.geogig.api.GeoGIG)

Example 2 with CommandFailedException

use of org.locationtech.geogig.cli.CommandFailedException in project GeoGig by boundlessgeo.

the class ShpExportDiff method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (args.size() != 4) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String commitOld = args.get(0);
    String commitNew = args.get(1);
    String path = args.get(2);
    String shapefile = args.get(3);
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
    File file = new File(shapefile);
    if (file.exists() && !overwrite) {
        throw new CommandFailedException("The selected shapefile already exists. Use -o to overwrite");
    }
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
    params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.FALSE);
    params.put(ShapefileDataStoreFactory.ENABLE_SPATIAL_INDEX.key, Boolean.FALSE);
    ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
    SimpleFeatureType outputFeatureType;
    try {
        outputFeatureType = getFeatureType(path, cli);
    } catch (GeoToolsOpException e) {
        cli.getConsole().println("No features to export.");
        return;
    }
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.add("geogig_fid", String.class);
    for (AttributeDescriptor descriptor : outputFeatureType.getAttributeDescriptors()) {
        builder.add(descriptor);
    }
    builder.setName(outputFeatureType.getName());
    builder.setCRS(outputFeatureType.getCoordinateReferenceSystem());
    outputFeatureType = builder.buildFeatureType();
    dataStore.createSchema(outputFeatureType);
    final String typeName = dataStore.getTypeNames()[0];
    final SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
    if (!(featureSource instanceof SimpleFeatureStore)) {
        throw new CommandFailedException("Could not create feature store.");
    }
    final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    Function<Feature, Optional<Feature>> function = getTransformingFunction(dataStore.getSchema());
    ExportDiffOp op = cli.getGeogig().command(ExportDiffOp.class).setFeatureStore(featureStore).setPath(path).setOldRef(commitOld).setNewRef(commitNew).setUseOld(old).setTransactional(false).setFeatureTypeConversionFunction(function);
    try {
        op.setProgressListener(cli.getProgressListener()).call();
    } catch (IllegalArgumentException iae) {
        throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
        file.delete();
        switch(e.statusCode) {
            case MIXED_FEATURE_TYPES:
                throw new CommandFailedException("Error: The selected tree contains mixed feature types.", e);
            default:
                throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
        }
    }
    cli.getConsole().println(path + " exported successfully to " + shapefile);
}
Also used : Serializable(java.io.Serializable) ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) Optional(com.google.common.base.Optional) HashMap(java.util.HashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ExportDiffOp(org.locationtech.geogig.geotools.plumbing.ExportDiffOp) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) Feature(org.opengis.feature.Feature) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ShapefileDataStoreFactory(org.geotools.data.shapefile.ShapefileDataStoreFactory) File(java.io.File)

Example 3 with CommandFailedException

use of org.locationtech.geogig.cli.CommandFailedException in project GeoGig by boundlessgeo.

the class ShpImport method runInternal.

/**
     * Executes the import command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(shapeFile != null && !shapeFile.isEmpty(), "No shapefile specified");
    for (String shp : shapeFile) {
        DataStore dataStore = null;
        try {
            dataStore = getDataStore(shp);
        } catch (InvalidParameterException e) {
            cli.getConsole().println("The shapefile '" + shp + "' could not be found, skipping...");
            continue;
        }
        if (fidAttribute != null) {
            AttributeDescriptor attrib = dataStore.getSchema(dataStore.getNames().get(0)).getDescriptor(fidAttribute);
            if (attrib == null) {
                throw new InvalidParameterException("The specified attribute does not exist in the selected shapefile");
            }
        }
        try {
            cli.getConsole().println("Importing from shapefile " + shp);
            ProgressListener progressListener = cli.getProgressListener();
            ImportOp command = cli.getGeogig().command(ImportOp.class).setAll(true).setTable(null).setAlter(alter).setOverwrite(!add).setDestinationPath(destTable).setDataStore(dataStore).setFidAttribute(fidAttribute).setAdaptToDefaultFeatureType(!forceFeatureType);
            // force the import not to use paging due to a bug in the shapefile datastore
            command.setUsePaging(false);
            command.setProgressListener(progressListener).call();
            cli.getConsole().println(shp + " imported successfully.");
        } catch (GeoToolsOpException e) {
            switch(e.statusCode) {
                case NO_FEATURES_FOUND:
                    throw new CommandFailedException("No features were found in the shapefile.", e);
                case UNABLE_TO_GET_NAMES:
                    throw new CommandFailedException("Unable to get feature types from the shapefile.", e);
                case UNABLE_TO_GET_FEATURES:
                    throw new CommandFailedException("Unable to get features from the shapefile.", e);
                case UNABLE_TO_INSERT:
                    throw new CommandFailedException("Unable to insert features into the working tree.", e);
                case INCOMPATIBLE_FEATURE_TYPE:
                    throw new CommandFailedException("The feature type of the data to import does not match the feature type of the destination tree and cannot be imported\n" + "USe the --force-featuretype switch to import using the original featuretype and crete a mixed type tree", e);
                default:
                    throw new CommandFailedException("Import failed with exception: " + e.statusCode.name(), e);
            }
        } finally {
            dataStore.dispose();
            cli.getConsole().flush();
        }
    }
}
Also used : InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) ProgressListener(org.locationtech.geogig.api.ProgressListener) DataStore(org.geotools.data.DataStore) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) ImportOp(org.locationtech.geogig.geotools.plumbing.ImportOp) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException)

Example 4 with CommandFailedException

use of org.locationtech.geogig.cli.CommandFailedException in project GeoGig by boundlessgeo.

the class Revert method runInternal.

/**
     * Executes the revert command.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(commits.size() > 0 || abort || continueRevert, "nothing specified for reverting");
    final GeoGIG geogig = cli.getGeogig();
    RevertOp revert = geogig.command(RevertOp.class);
    for (String st : commits) {
        Optional<ObjectId> commitId = geogig.command(RevParse.class).setRefSpec(st).call();
        checkParameter(commitId.isPresent(), "Couldn't resolve '" + st + "' to a commit, aborting revert.");
        revert.addCommit(Suppliers.ofInstance(commitId.get()));
    }
    try {
        revert.setCreateCommit(!noCommit).setAbort(abort).setContinue(continueRevert).call();
    } catch (RevertConflictsException e) {
        StringBuilder sb = new StringBuilder();
        sb.append(e.getMessage() + "\n");
        sb.append("When you have fixed these conflicts, run 'geogig revert --continue' to continue the revert operation.\n");
        sb.append("To abort the revert operation, run 'geogig revert --abort'\n");
        throw new CommandFailedException(sb.toString());
    }
    if (abort) {
        cli.getConsole().println("Revert aborted successfully.");
    }
}
Also used : RevertOp(org.locationtech.geogig.api.porcelain.RevertOp) ObjectId(org.locationtech.geogig.api.ObjectId) RevertConflictsException(org.locationtech.geogig.api.porcelain.RevertConflictsException) GeoGIG(org.locationtech.geogig.api.GeoGIG) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException)

Example 5 with CommandFailedException

use of org.locationtech.geogig.cli.CommandFailedException in project GeoGig by boundlessgeo.

the class Merge method runInternal.

/**
     * Executes the merge command using the provided options.
     */
@Override
public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(commits.size() > 0 || abort, "No commits provided to merge.");
    ConsoleReader console = cli.getConsole();
    final GeoGIG geogig = cli.getGeogig();
    Ansi ansi = newAnsi(console.getTerminal());
    if (abort) {
        Optional<Ref> ref = geogig.command(RefParse.class).setName(Ref.ORIG_HEAD).call();
        if (!ref.isPresent()) {
            throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>.");
        }
        geogig.command(ResetOp.class).setMode(ResetMode.HARD).setCommit(Suppliers.ofInstance(ref.get().getObjectId())).call();
        console.println("Merge aborted successfully.");
        return;
    }
    RevCommit commit;
    try {
        MergeOp merge = geogig.command(MergeOp.class);
        merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit);
        merge.setMessage(message).setProgressListener(cli.getProgressListener());
        for (String commitish : commits) {
            Optional<ObjectId> commitId;
            commitId = geogig.command(RevParse.class).setRefSpec(commitish).call();
            checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish);
            merge.addCommit(Suppliers.ofInstance(commitId.get()));
        }
        MergeReport report = merge.call();
        commit = report.getMergeCommit();
    } catch (RuntimeException e) {
        if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) {
            throw new CommandFailedException(e.getMessage(), e);
        }
        throw e;
    }
    final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL);
    console.println("[" + commit.getId() + "] " + commit.getMessage());
    console.print("Committed, counting objects...");
    Iterator<DiffEntry> diff = geogig.command(DiffOp.class).setOldVersion(parentId).setNewVersion(commit.getId()).call();
    int adds = 0, deletes = 0, changes = 0;
    DiffEntry diffEntry;
    while (diff.hasNext()) {
        diffEntry = diff.next();
        switch(diffEntry.changeType()) {
            case ADDED:
                ++adds;
                break;
            case REMOVED:
                ++deletes;
                break;
            case MODIFIED:
                ++changes;
                break;
        }
    }
    ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes).reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset().newline();
    console.print(ansi.toString());
}
Also used : ConsoleReader(jline.console.ConsoleReader) ObjectId(org.locationtech.geogig.api.ObjectId) NothingToCommitException(org.locationtech.geogig.api.porcelain.NothingToCommitException) DiffOp(org.locationtech.geogig.api.porcelain.DiffOp) MergeOp(org.locationtech.geogig.api.porcelain.MergeOp) ResetOp(org.locationtech.geogig.api.porcelain.ResetOp) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) MergeReport(org.locationtech.geogig.api.porcelain.MergeOp.MergeReport) Ref(org.locationtech.geogig.api.Ref) RevParse(org.locationtech.geogig.api.plumbing.RevParse) Ansi(org.fusesource.jansi.Ansi) GeoGIG(org.locationtech.geogig.api.GeoGIG) RevCommit(org.locationtech.geogig.api.RevCommit) DiffEntry(org.locationtech.geogig.api.plumbing.diff.DiffEntry)

Aggregations

CommandFailedException (org.locationtech.geogig.cli.CommandFailedException)58 DataStore (org.geotools.data.DataStore)28 GeoToolsOpException (org.locationtech.geogig.geotools.plumbing.GeoToolsOpException)24 File (java.io.File)16 GeoGIG (org.locationtech.geogig.api.GeoGIG)16 ObjectId (org.locationtech.geogig.api.ObjectId)15 IOException (java.io.IOException)14 InvalidParameterException (org.locationtech.geogig.cli.InvalidParameterException)12 ConsoleReader (jline.console.ConsoleReader)10 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)10 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)10 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)10 ExportOp (org.locationtech.geogig.geotools.plumbing.ExportOp)9 Serializable (java.io.Serializable)8 Optional (com.google.common.base.Optional)7 TYPE (org.locationtech.geogig.api.RevObject.TYPE)7 Map (java.util.Map)6 ProgressListener (org.locationtech.geogig.api.ProgressListener)6 Connection (java.sql.Connection)4 Feature (org.opengis.feature.Feature)4