List of usage examples for com.google.common.base Optional orNull
@Nullable public abstract T orNull();
From source file:org.locationtech.geogig.geotools.data.GeogigTransactionState.java
@Override public void commit() throws IOException { Preconditions.checkState(this.geogigTx != null); /*/*from w w w.ja v a2s.c o m*/ * This follows suite with the hack set on GeoSever's * org.geoserver.wfs.Transaction.getDatastoreTransaction() */ final Optional<String> txUserName = getTransactionProperty(VERSIONING_COMMIT_AUTHOR); final Optional<String> fullName = getTransactionProperty("fullname"); final Optional<String> email = getTransactionProperty("email"); final String author = fullName.isPresent() ? fullName.get() : txUserName.orNull(); String commitMessage = getTransactionProperty(VERSIONING_COMMIT_MESSAGE).orNull(); this.geogigTx.command(AddOp.class).call(); try { CommitOp commitOp = this.geogigTx.command(CommitOp.class); if (txUserName != null) { commitOp.setAuthor(author, email.orNull()); } if (commitMessage == null) { commitMessage = composeDefaultCommitMessage(); } commitOp.setMessage(commitMessage); commitOp.call(); } catch (NothingToCommitException nochanges) { // ok } try { this.geogigTx.setAuthor(author, email.orNull()).commit(); } catch (ConflictsException e) { // TODO: how should this be handled? this.geogigTx.abort(); } this.geogigTx = null; }
From source file:org.locationtech.geogig.storage.StorageType.java
/** * Adds configuration properties to the {@link ConfigDatabase} with the format name and version * of this storage type.//from ww w .ja va 2s . c o m * * @param configDB the config database * @param formatName the format name of the storage type * @param version the version of the storage format * @throws RepositoryConnectionException */ public void configure(ConfigDatabase configDB, String formatName, String version) throws RepositoryConnectionException { Optional<String> storageName = configDB.get("storage." + key); Optional<String> storageVersion = configDB.get(formatName + ".version"); if (storageName.isPresent() && !storageName.get().equals(formatName)) { throw new RepositoryConnectionException( "Initializing already " + "initialized " + key + " database. Would set " + formatName + ":" + version + " but found " + storageName.orNull() + ":" + storageVersion.orNull()); } if (storageVersion.isPresent() && !version.equals(storageVersion.get())) { throw new RepositoryConnectionException( "Initializing already " + "initialized " + key + " database. Would set " + formatName + ":" + version + " but found " + storageName.orNull() + ":" + storageVersion.orNull()); } configDB.put("storage." + key, formatName); configDB.put(formatName + ".version", version); }
From source file:com.forerunnergames.tools.net.DefaultExternalAddressResolver.java
/** * Attempt to use the specified URL('s) to resolve the external ip address of the local machine. * * @return A valid ip address string such that {@link InetAddresses#isInetAddress(String)} returns true, or an empty * string if no valid ip address could be resolved from the supplied URL('s). *///from w w w. j a v a 2 s. c o m @Override public String resolveIp() { for (final String url : urls) { final Optional<String> ipAddress = readIpAddressFrom(url); if (isValid(ipAddress)) { log.debug("Successfully resolved external IP address [{}] from URL [{}].", ipAddress.get(), url); return ipAddress.get(); } if (!alreadyLoggedErrorMessage) { log.error("Could not resolve external IP address [{}] using URL [{}]", ipAddress.orNull(), url); } } log.error( "Could not resolve external IP address using the specified URL('s):\n\n[{}]\n\nThe returned ip address will be empty.", urls); return ""; }
From source file:org.geogit.api.porcelain.RemoteResolve.java
/** * Executes the remote-add operation./*from w w w .j a va 2 s . c om*/ * * @return the {@link Remote} that was added. */ @Override public Optional<Remote> call() { if (name == null || name.isEmpty()) { throw new RemoteException(StatusCode.MISSING_NAME); } Optional<Remote> result = Optional.absent(); List<String> allRemotes = config.getAllSubsections("remote"); if (allRemotes.contains(name)) { String remoteSection = "remote." + name; Optional<String> remoteFetchURL = config.get(remoteSection + ".url"); Optional<String> remoteFetch = config.get(remoteSection + ".fetch"); Optional<String> remoteMapped = config.get(remoteSection + ".mapped"); Optional<String> remoteMappedBranch = config.get(remoteSection + ".mappedBranch"); if (remoteFetchURL.isPresent() && remoteFetch.isPresent()) { Optional<String> remotePushURL = config.get(remoteSection + ".pushurl"); Remote remote = new Remote(name, remoteFetchURL.get(), remotePushURL.or(remoteFetchURL.get()), remoteFetch.get(), remoteMapped.or("false").equals("true"), remoteMappedBranch.orNull()); result = Optional.of(remote); } } return result; }
From source file:org.apache.usergrid.corepersistence.pipeline.read.traverse.AbstractReadReverseGraphFilter.java
@Override public Observable<FilterResult<Id>> call(final Observable<FilterResult<Id>> previousIds) { final ApplicationScope applicationScope = pipelineContext.getApplicationScope(); //get the graph manager final GraphManager graphManager = graphManagerFactory.createEdgeManager(applicationScope); final String edgeName = getEdgeTypeName(); final EdgeState edgeCursorState = new EdgeState(); //return all ids that are emitted from this edge return previousIds.flatMap(previousFilterValue -> { //set our our constant state final Optional<MarkedEdge> startFromCursor = getSeekValue(); final Id id = previousFilterValue.getValue(); final Optional<Edge> typeWrapper = Optional.fromNullable(startFromCursor.orNull()); /**/* ww w .ja va2s. c o m*/ * We do not want to filter. This is intentional DO NOT REMOVE!!! * * We want to fire events on these edges if they exist, the delete was missed. */ final SimpleSearchByEdgeType search = new SimpleSearchByEdgeType(id, edgeName, Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING, typeWrapper, false); /** * TODO, pass a message with pointers to our cursor values to be generated later */ return graphManager.loadEdgesToTarget(search).filter(markedEdge -> { final boolean isDeleted = markedEdge.isDeleted(); final boolean isSourceNodeDeleted = markedEdge.isSourceNodeDelete(); final boolean isTargetNodeDelete = markedEdge.isTargetNodeDeleted(); if (isDeleted) { logger.info("Edge {} is deleted when seeking, deleting the edge", markedEdge); final Observable<IndexOperationMessage> indexMessageObservable = eventBuilder .buildDeleteEdge(applicationScope, markedEdge); indexMessageObservable.compose(applyCollector()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); } if (isSourceNodeDeleted) { final Id sourceNodeId = markedEdge.getSourceNode(); logger.info("Edge {} has a deleted source node, deleting the entity for id {}", markedEdge, sourceNodeId); final EventBuilderImpl.EntityDeleteResults entityDeleteResults = eventBuilder .buildEntityDelete(applicationScope, sourceNodeId); entityDeleteResults.getIndexObservable().compose(applyCollector()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); Observable .merge(entityDeleteResults.getEntitiesDeleted(), entityDeleteResults.getCompactedNode()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); } if (isTargetNodeDelete) { final Id targetNodeId = markedEdge.getTargetNode(); logger.info("Edge {} has a deleted target node, deleting the entity for id {}", markedEdge, targetNodeId); final EventBuilderImpl.EntityDeleteResults entityDeleteResults = eventBuilder .buildEntityDelete(applicationScope, targetNodeId); entityDeleteResults.getIndexObservable().compose(applyCollector()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); Observable .merge(entityDeleteResults.getEntitiesDeleted(), entityDeleteResults.getCompactedNode()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); } //filter if any of them are marked return !isDeleted && !isSourceNodeDeleted && !isTargetNodeDelete; }) // any non-deleted edges should be de-duped here so the results are unique .distinct(new EdgeDistinctKey()) //set the edge state for cursors .doOnNext(edge -> { if (logger.isTraceEnabled()) { logger.trace("Seeking over edge {}", edge); } edgeCursorState.update(edge); }) //map our id from the target edge and set our cursor every edge we traverse .map(edge -> createFilterResult(edge.getSourceNode(), edgeCursorState.getCursorEdge(), previousFilterValue.getPath())); }); }
From source file:com.github.autermann.wps.streaming.message.xml.AbstractMessageEncoding.java
private void decodeAction(T message, ActionDocument actionDocument) { Optional<URI> action = parseURI(actionDocument.getAction().getStringValue()); if (!action.isPresent() || !action.get().equals(message.getSOAPAction())) { log.warn("SOAP action mismatch: {} vs {}", message.getSOAPAction(), action.orNull()); }//from w w w .ja va2s.com }
From source file:org.apache.usergrid.persistence.graph.impl.stage.NodeDeleteListenerImpl.java
/** * Removes this node from the graph.//ww w . j av a2 s .c om * * @param scope The scope of the application * @param node The node that was deleted * @param timestamp The timestamp of the event * * @return An observable that emits the total number of edges that have been removed with this node both as the * target and source */ public Observable<Integer> receive(final ApplicationScope scope, final Id node, final UUID timestamp) { return Observable.just(node) //delete source and targets in parallel and merge them into a single observable .flatMap(new Func1<Id, Observable<Integer>>() { @Override public Observable<Integer> call(final Id node) { final Optional<Long> maxVersion = nodeSerialization.getMaxVersion(scope, node); if (logger.isTraceEnabled()) { logger.trace("Node with id {} has max version of {}", node, maxVersion.orNull()); } if (!maxVersion.isPresent()) { return Observable.empty(); } //do all the delete, then when done, delete the node return doDeletes(node, scope, maxVersion.get(), timestamp).count() //if nothing is ever emitted, emit 0 so that we know no operations took place. // Finally remove // the // target node in the mark .doOnCompleted(new Action0() { @Override public void call() { try { nodeSerialization.delete(scope, node, maxVersion.get()).execute(); } catch (ConnectionException e) { throw new RuntimeException("Unable to connect to casandra", e); } } }); } }).defaultIfEmpty(0); }
From source file:org.apache.usergrid.corepersistence.pipeline.read.traverse.AbstractReadGraphFilter.java
@Override public Observable<FilterResult<Id>> call(final Observable<FilterResult<Id>> previousIds) { final ApplicationScope applicationScope = pipelineContext.getApplicationScope(); //get the graph manager final GraphManager graphManager = graphManagerFactory.createEdgeManager(applicationScope); final String edgeName = getEdgeTypeName(); final EdgeState edgeCursorState = new EdgeState(); //return all ids that are emitted from this edge return previousIds.flatMap(previousFilterValue -> { //set our our constant state final Optional<MarkedEdge> startFromCursor = getSeekValue(); final Id id = previousFilterValue.getValue(); final Optional<Edge> typeWrapper = Optional.fromNullable(startFromCursor.orNull()); /**/* w ww. j a v a2s . co m*/ * We do not want to filter. This is intentional DO NOT REMOVE!!! * * We want to fire events on these edges if they exist, the delete was missed. */ final SimpleSearchByEdgeType search = new SimpleSearchByEdgeType(id, edgeName, Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING, typeWrapper, false); /** * TODO, pass a message with pointers to our cursor values to be generated later */ return graphManager.loadEdgesFromSource(search).filter(markedEdge -> { final boolean isDeleted = markedEdge.isDeleted(); final boolean isSourceNodeDeleted = markedEdge.isSourceNodeDelete(); final boolean isTargetNodeDelete = markedEdge.isTargetNodeDeleted(); if (isDeleted) { logger.info("Edge {} is deleted when seeking, deleting the edge", markedEdge); final Observable<IndexOperationMessage> indexMessageObservable = eventBuilder .buildDeleteEdge(applicationScope, markedEdge); indexMessageObservable.compose(applyCollector()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); } if (isSourceNodeDeleted) { final Id sourceNodeId = markedEdge.getSourceNode(); logger.info("Edge {} has a deleted source node, deleting the entity for id {}", markedEdge, sourceNodeId); final EventBuilderImpl.EntityDeleteResults entityDeleteResults = eventBuilder .buildEntityDelete(applicationScope, sourceNodeId); entityDeleteResults.getIndexObservable().compose(applyCollector()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); Observable .merge(entityDeleteResults.getEntitiesDeleted(), entityDeleteResults.getCompactedNode()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); } if (isTargetNodeDelete) { final Id targetNodeId = markedEdge.getTargetNode(); logger.info("Edge {} has a deleted target node, deleting the entity for id {}", markedEdge, targetNodeId); final EventBuilderImpl.EntityDeleteResults entityDeleteResults = eventBuilder .buildEntityDelete(applicationScope, targetNodeId); entityDeleteResults.getIndexObservable().compose(applyCollector()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); Observable .merge(entityDeleteResults.getEntitiesDeleted(), entityDeleteResults.getCompactedNode()) .subscribeOn(rxTaskScheduler.getAsyncIOScheduler()).subscribe(); } //filter if any of them are marked return !isDeleted && !isSourceNodeDeleted && !isTargetNodeDelete; }) // any non-deleted edges should be de-duped here so the results are unique .distinct(new EdgeDistinctKey()) //set the edge state for cursors .doOnNext(edge -> { if (logger.isTraceEnabled()) { logger.trace("Seeking over edge {}", edge); } edgeCursorState.update(edge); }) //map our id from the target edge and set our cursor every edge we traverse .map(edge -> createFilterResult(edge.getTargetNode(), edgeCursorState.getCursorEdge(), previousFilterValue.getPath())); }); }
From source file:org.opendaylight.distributed.tx.impl.CachingReadWriteTx.java
public <T extends DataObject> CheckedFuture<Void, DTxException> asyncMerge( final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier, final T t) { increaseOperation();/* w ww .j ava 2s.c om*/ CheckedFuture<Optional<T>, ReadFailedException> readFuture = null; try { readFuture = delegate.read(logicalDatastoreType, instanceIdentifier); } catch (Exception e) { readFuture = Futures .immediateFailedCheckedFuture(new ReadFailedException("Read exception in merge action")); } final SettableFuture<Void> retFuture = SettableFuture.create(); Futures.addCallback(readFuture, new FutureCallback<Optional<T>>() { @Override public void onSuccess(final Optional<T> result) { synchronized (this) { cache.add(new CachedData(logicalDatastoreType, instanceIdentifier, result.orNull(), ModifyAction.MERGE)); } final ListeningExecutorService executorService = MoreExecutors .listeningDecorator(executorPoolPerCache); final ListenableFuture asyncMergeFuture = executorService.submit(new Callable() { @Override public Object call() throws Exception { delegate.merge(logicalDatastoreType, instanceIdentifier, t); return null; } }); Futures.addCallback(asyncMergeFuture, new FutureCallback() { @Override public void onSuccess(@Nullable Object result) { decreaseOperation(); retFuture.set(null); } @Override public void onFailure(Throwable t) { decreaseOperation(); LOG.trace("async merge failure"); retFuture.setException(new DTxException.EditFailedException("async merge failure", t)); } }); } @Override public void onFailure(final Throwable t) { decreaseOperation(); retFuture.setException( new DTxException.ReadFailedException("failed to read from node in merge action", t)); } }); return Futures.makeChecked(retFuture, new Function<Exception, DTxException>() { @Nullable @Override public DTxException apply(@Nullable Exception e) { e = (Exception) e.getCause(); return e instanceof DTxException ? (DTxException) e : new DTxException("merge operation failed", e); } }); }
From source file:com.github.jsdossier.JsDoc.java
private boolean hasAnnotation(Annotation target) { for (Marker marker : info.getMarkers()) { Optional<Annotation> annotation = Annotation.forMarker(marker); if (target.equals(annotation.orNull())) { return true; }//from w w w . j av a2 s . c om } return false; }