use of com.google.common.base.Optional 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);
}
use of com.google.common.base.Optional in project GeoGig by boundlessgeo.
the class ExportDiffOp method _call.
/**
* Executes the export operation using the parameters that have been specified.
*
* @return a FeatureCollection with the specified features
*/
@Override
protected SimpleFeatureStore _call() {
final SimpleFeatureStore targetStore = getTargetStore();
final String refspec = old ? oldRef : newRef;
final RevTree rootTree = resolveRootTree(refspec);
final NodeRef typeTreeRef = resolTypeTreeRef(refspec, path, rootTree);
final ObjectId defaultMetadataId = typeTreeRef.getMetadataId();
final ProgressListener progressListener = getProgressListener();
progressListener.started();
progressListener.setDescription("Exporting diffs for path '" + path + "'... ");
FeatureCollection<SimpleFeatureType, SimpleFeature> asFeatureCollection = new BaseFeatureCollection<SimpleFeatureType, SimpleFeature>() {
@Override
public FeatureIterator<SimpleFeature> features() {
Iterator<DiffEntry> diffs = command(DiffOp.class).setOldVersion(oldRef).setNewVersion(newRef).setFilter(path).call();
final Iterator<SimpleFeature> plainFeatures = getFeatures(diffs, old, stagingDatabase(), defaultMetadataId, progressListener);
Iterator<Optional<Feature>> transformed = Iterators.transform(plainFeatures, ExportDiffOp.this.function);
Iterator<SimpleFeature> filtered = Iterators.filter(Iterators.transform(transformed, new Function<Optional<Feature>, SimpleFeature>() {
@Override
public SimpleFeature apply(Optional<Feature> input) {
return (SimpleFeature) (input.isPresent() ? input.get() : null);
}
}), Predicates.notNull());
return new DelegateFeatureIterator<SimpleFeature>(filtered);
}
};
// add the feature collection to the feature store
final Transaction transaction;
if (transactional) {
transaction = new DefaultTransaction("create");
} else {
transaction = Transaction.AUTO_COMMIT;
}
try {
targetStore.setTransaction(transaction);
try {
targetStore.addFeatures(asFeatureCollection);
transaction.commit();
} catch (final Exception e) {
if (transactional) {
transaction.rollback();
}
Throwables.propagateIfInstanceOf(e, GeoToolsOpException.class);
throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
} finally {
transaction.close();
}
} catch (IOException e) {
throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
}
progressListener.complete();
return targetStore;
}
use of com.google.common.base.Optional in project GeoGig by boundlessgeo.
the class RevertFeatureWebOp method run.
/**
* Runs the command and builds the appropriate response
*
* @param context - the context to use for this command
*
* @throws CommandSpecException
*/
@Override
public void run(CommandContext context) {
if (this.getTransactionId() == null) {
throw new CommandSpecException("No transaction was specified, revert feature requires a transaction to preserve the stability of the repository.");
}
final Context geogig = this.getCommandLocator(context);
Optional<RevTree> newTree = Optional.absent();
Optional<RevTree> oldTree = Optional.absent();
// get tree from new commit
Optional<ObjectId> treeId = geogig.command(ResolveTreeish.class).setTreeish(newCommitId).call();
Preconditions.checkState(treeId.isPresent(), "New commit id did not resolve to a valid tree.");
newTree = geogig.command(RevObjectParse.class).setRefSpec(treeId.get().toString()).call(RevTree.class);
Preconditions.checkState(newTree.isPresent(), "Unable to read the new commit tree.");
// get tree from old commit
treeId = geogig.command(ResolveTreeish.class).setTreeish(oldCommitId).call();
Preconditions.checkState(treeId.isPresent(), "Old commit id did not resolve to a valid tree.");
oldTree = geogig.command(RevObjectParse.class).setRefSpec(treeId.get().toString()).call(RevTree.class);
Preconditions.checkState(newTree.isPresent(), "Unable to read the old commit tree.");
// get feature from old tree
Optional<NodeRef> node = geogig.command(FindTreeChild.class).setParent(oldTree.get()).setIndex(true).setChildPath(featurePath).call();
boolean delete = false;
if (!node.isPresent()) {
delete = true;
node = geogig.command(FindTreeChild.class).setParent(newTree.get()).setIndex(true).setChildPath(featurePath).call();
Preconditions.checkState(node.isPresent(), "The feature was not found in either commit tree.");
}
// get the new parent tree
ObjectId metadataId = ObjectId.NULL;
Optional<NodeRef> parentNode = geogig.command(FindTreeChild.class).setParent(newTree.get()).setChildPath(node.get().getParentPath()).setIndex(true).call();
RevTreeBuilder treeBuilder = null;
if (parentNode.isPresent()) {
metadataId = parentNode.get().getMetadataId();
Optional<RevTree> parsed = geogig.command(RevObjectParse.class).setObjectId(parentNode.get().getNode().getObjectId()).call(RevTree.class);
checkState(parsed.isPresent(), "Parent tree couldn't be found in the repository.");
treeBuilder = new RevTreeBuilder(geogig.stagingDatabase(), parsed.get());
treeBuilder.remove(node.get().getNode().getName());
} else {
treeBuilder = new RevTreeBuilder(geogig.stagingDatabase());
}
// put the old feature into the new tree
if (!delete) {
treeBuilder.put(node.get().getNode());
}
ObjectId newTreeId = geogig.command(WriteBack.class).setAncestor(newTree.get().builder(geogig.stagingDatabase())).setChildPath(node.get().getParentPath()).setToIndex(true).setTree(treeBuilder.build()).setMetadataId(metadataId).call();
// build new commit with parent of new commit and the newly built tree
CommitBuilder builder = new CommitBuilder();
builder.setParentIds(Lists.newArrayList(newCommitId));
builder.setTreeId(newTreeId);
builder.setAuthor(authorName.orNull());
builder.setAuthorEmail(authorEmail.orNull());
builder.setMessage(commitMessage.or("Reverted changes made to " + featurePath + " at " + newCommitId.toString()));
RevCommit mapped = builder.build();
context.getGeoGIG().getRepository().objectDatabase().put(mapped);
// merge commit into current branch
final Optional<Ref> currHead = geogig.command(RefParse.class).setName(Ref.HEAD).call();
if (!currHead.isPresent()) {
throw new CommandSpecException("Repository has no HEAD, can't merge.");
}
MergeOp merge = geogig.command(MergeOp.class);
merge.setAuthor(authorName.orNull(), authorEmail.orNull());
merge.addCommit(Suppliers.ofInstance(mapped.getId()));
merge.setMessage(mergeMessage.or("Merged revert of " + featurePath));
try {
final MergeReport report = merge.call();
context.setResponseContent(new CommandResponse() {
@Override
public void write(ResponseWriter out) throws Exception {
out.start();
out.writeMergeResponse(Optional.fromNullable(report.getMergeCommit()), report.getReport().get(), geogig, report.getOurs(), report.getPairs().get(0).getTheirs(), report.getPairs().get(0).getAncestor());
out.finish();
}
});
} catch (Exception e) {
final RevCommit ours = context.getGeoGIG().getRepository().getCommit(currHead.get().getObjectId());
final RevCommit theirs = context.getGeoGIG().getRepository().getCommit(mapped.getId());
final Optional<ObjectId> ancestor = geogig.command(FindCommonAncestor.class).setLeft(ours).setRight(theirs).call();
context.setResponseContent(new CommandResponse() {
final MergeScenarioReport report = geogig.command(ReportMergeScenarioOp.class).setMergeIntoCommit(ours).setToMergeCommit(theirs).call();
@Override
public void write(ResponseWriter out) throws Exception {
out.start();
Optional<RevCommit> mergeCommit = Optional.absent();
out.writeMergeResponse(mergeCommit, report, geogig, ours.getId(), theirs.getId(), ancestor.get());
out.finish();
}
});
}
}
use of com.google.common.base.Optional in project core-java by SpineEventEngine.
the class MessageRouting method doRoute.
/**
* Sets a custom route for the passed message class.
*
* <p>Such a mapping may be required when...
* <ul>
* <li>A message should be matched to more than one entity.
* <li>The type of an message producer ID (stored in the message context) differs from the
* type of entity identifiers.
* </ul>
*
* <p>If there is no specific route for the class of the passed message, the routing will use
* the {@linkplain #getDefault() default route}.
*
* @param messageClass the class of messages to route
* @param via the instance of the route to be used
* @param <M> the type of the message
* @throws IllegalStateException if the route for this message class is already set
*/
<M extends Message> MessageRouting<C, K, R> doRoute(Class<M> messageClass, Route<Message, C, R> via) throws IllegalStateException {
checkNotNull(messageClass);
checkNotNull(via);
final Optional route = doGet(messageClass);
if (route.isPresent()) {
throw newIllegalStateException("The route for the message class %s already set. " + "Please remove the route (%s) before setting new route.", messageClass.getName(), route.get());
}
final K cls = toMessageClass(messageClass);
routes.put(cls, via);
return this;
}
use of com.google.common.base.Optional in project core-java by SpineEventEngine.
the class PairShould method return_Empty_for_absent_Optional_in_iterator.
@Test
public void return_Empty_for_absent_Optional_in_iterator() {
StringValue a = TestValues.newUuidValue();
Pair<StringValue, Optional<BoolValue>> pair = Pair.withNullable(a, null);
final Iterator<Message> iterator = pair.iterator();
assertEquals(a, iterator.next());
assertEquals(Empty.getDefaultInstance(), iterator.next());
assertFalse(iterator.hasNext());
}
Aggregations