List of usage examples for com.google.common.util.concurrent Futures immediateCheckedFuture
@GwtIncompatible("TODO") @CheckReturnValue public static <V, X extends Exception> CheckedFuture<V, X> immediateCheckedFuture(@Nullable V value)
From source file:com.toro.torod.connection.DefaultToroTransaction.java
@Override public ListenableFuture<UpdateResponse> update(String collection, List<? extends UpdateOperation> updates, WriteFailMode mode, UpdateActionVisitor<ToroDocument, Void> updateActionVisitorDocumentToInsert, UpdateActionVisitor<UpdatedToroDocument, ToroDocument> updateActionVisitorDocumentToUpdate) { cache.createCollection(executor, collection, null); UpdateResponse.Builder builder = new UpdateResponse.Builder(); for (int updateIndex = 0; updateIndex < updates.size(); updateIndex++) { UpdateOperation update = updates.get(updateIndex); try {/*from w w w. j ava2 s . c om*/ update(collection, update, updateIndex, updateActionVisitorDocumentToInsert, updateActionVisitorDocumentToUpdate, builder); } catch (InterruptedException | ExecutionException | RetryTransactionException ex) { return Futures.immediateFailedCheckedFuture(ex); } catch (UserToroException ex) { builder.addError(new WriteError(updateIndex, -1, ex.getLocalizedMessage())); } } return Futures.immediateCheckedFuture(builder.build()); }
From source file:org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver.java
@Override public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource( final SourceIdentifier sourceIdentifier) { final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier); LOG.debug("Lookup {} result {}", sourceIdentifier, ret); if (ret.isEmpty()) { return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException( "URL for " + sourceIdentifier + " not registered", sourceIdentifier)); }/*from www. j a va 2s . c o m*/ return Futures.immediateCheckedFuture(ret.iterator().next()); }
From source file:org.opendaylight.yangpush.rpc.YangpushRpcImpl.java
/** * This method is invoked on RPC invocation of the registered method. * rpc(localname) is used to invoke the correct requested method. *//* ww w. j a va 2s .c o m*/ @Override public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(DOMRpcIdentifier rpc, NormalizedNode<?, ?> input) { if (rpc.equals(CREATE_SUBSCRIPTION_RPC)) { LOG.debug("This is a create subscription RPC"); return createSubscriptionRpcHandler(input); } else if (rpc.equals(MODIFY_SUBSCRIPTION_RPC)) { LOG.info("This is a modify subscrition RPC. Not supported ..."); } else if (rpc.equals(DELETE_SUBSCRIPTION_RPC)) { deleteSubscriptionRpcHandler(input); } else { LOG.info("Unknown RPC..."); } return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult()); }
From source file:ncmount.impl.NcmountDomProvider.java
/** * This method is the implementation of the 'list-nodes' RESTCONF service, * which is one of the external APIs into the ncmount application. The * service provides two example functions: * 1. Lists nodes in the Netconf Topology's configuration data * 2. Lists nodes in the Netconf Topology's operational data * * Netconf Topology is populated by the Netconf Connector. Configuration * data contains the configuration data for each netconf node configured in * the Netconf Connector. Operational data contains status data for each * netconf node configured in the Netconf Connector. * * @return Lists of nodes found in Netconf Topology's configuration and * operational spaces.//from w w w .ja v a 2 s .c o m */ private CheckedFuture<DOMRpcResult, DOMRpcException> listNodes() { LOG.info(" invoked RPC List-Node"); // created the leaf node to represent "leaf-list nc-config-nodes." LeafSetNode<Object> ncConfigLeafList = getNCConfigNodes(); // created the leaf node to represent "leaf-list nc-oper-nodes" LeafSetNode<Object> ncOperLeafList = getNCOperationalNodes(); // pack the output and return. ContainerNode resultNode = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(RPC_OUTPUT_QNAME)) .withChild(ncConfigLeafList).withChild(ncOperLeafList).build(); return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(resultNode)); }
From source file:org.opendaylight.netconf.test.tool.NetconfDeviceSimulator.java
private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) { consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() { @Override//from w ww . j a v a 2 s .co m public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource( final SourceIdentifier sourceIdentifier) { return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) { @Override protected MoreObjects.ToStringHelper addToStringAttributes( final MoreObjects.ToStringHelper toStringHelper) { return toStringHelper; } @Override public InputStream openStream() throws IOException { return getClass().getResourceAsStream(resource); } }); } }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue())); }
From source file:org.apache.shindig.social.websockbackend.spi.WsNativeMessageSPI.java
@Override public Future<Void> modifyMessage(UserId userId, String msgCollId, String messageId, Message message, SecurityToken token) throws ProtocolException { // set time stamp message.setUpdated(new Date(System.currentTimeMillis())); // create query final WebsockQuery query = new WebsockQuery(EQueryType.PROCEDURE_CALL); query.setPayload(ShindigNativeQueries.MODIFY_MESSAGE_QUERY); // set parameters for method query.setParameter(ShindigNativeQueries.USER_ID, userId.getUserId(token)); query.setParameter(ShindigNativeQueries.MESSAGE_COLLECTION_ID, msgCollId); query.setParameter(ShindigNativeQueries.MESSAGE_ID, messageId); final Map<String, Object> msgMap = new HashMap<String, Object>(); final MessageDTO dto = new MessageDTO(msgMap); dto.setData(message);//from w ww .j a v a 2 s .com dto.stripNullValues(); query.setParameter(ShindigNativeQueries.MESSAGE_OBJECT, msgMap); // execute try { this.fQueryHandler.sendQuery(query).get(); } catch (final Exception e) { e.printStackTrace(); this.fLogger.log(Level.SEVERE, "server error", e); throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not modify message", e); } // fire event if (this.fFireEvents) { try { // get modified message final List<String> msgIds = new ArrayList<String>(); msgIds.add(message.getId()); final List<Message> msgs = this .getMessages(userId, msgCollId, null, msgIds, new CollectionOptions(), token).get() .getList(); // send event if (msgs.size() > 0) { // prepare additional metadata final Map<String, String> props = new HashMap<String, String>(); if (token != null) { props.put("userId", userId.getUserId(token)); } else { props.put("userId", userId.getUserId()); } props.put("messageCollectionId", msgCollId); // fire event final Message newMess = msgs.get(0); final BasicEvent event = new BasicEvent(ShindigEventType.MESSAGE_UPDATED); event.setPayload(newMess); event.setToken(token); this.fEventBus.fireEvent(event); } } catch (final Exception e) { this.fLogger.log(Level.WARNING, "failed to send event", e); } } return Futures.immediateCheckedFuture(null); }
From source file:diskCacheV111.srm.dcache.Storage.java
@Override public CheckedFuture<String, ? extends SRMException> unPinFile(SRMUser user, String fileId, String pinId) { if (PinCompanion.isFakePinId(pinId)) { return Futures.immediateCheckedFuture(null); }// w ww.ja va2 s . co m try { Subject subject = (user == null) ? Subjects.ROOT : asDcacheUser(user).getSubject(); return Futures.makeChecked(UnpinCompanion.unpinFile(subject, new PnfsId(fileId), Long.parseLong(pinId), _pinManagerStub, _executor), new ToSRMException()); } catch (SRMAuthorizationException e) { return Futures.immediateFailedCheckedFuture(e); } }
From source file:org.opendaylight.yangpush.rpc.YangpushRpcImpl.java
/** * This method handles createSubscription RPC call. Parse the input and * based on that, creates subscription. and returns subscription-id for the * subscription. If the subscription Id is -1 then there is error in * subscriotion creation. Else a valid subscription id generated by this * method.//w w w .j a v a2s . c o m * * Subscription-id : "-1" -> represents error in subscription * Subscription-id : "yp-<integer>" -> represents the subscription id * created. This subscription-id should be used for all further * communication related to the subscription. * * @param input * @return */ private CheckedFuture<DOMRpcResult, DOMRpcException> createSubscriptionRpcHandler(NormalizedNode<?, ?> input) { String error = ""; String sid = ""; if (input.equals(null)) { sid = "-1"; LOG.error(YangpushErrors.printError(errors.input_error)); ContainerNode output = createCSOutPut(sid); return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(output)); } // Parse input arg CreateSubscriptionRpcInput inputData = parseExternalRpcInput(input, error); if (inputData.equals(null)) { System.out.println(error); LOG.error(error); sid = "-1"; error = null; ContainerNode output = createCSOutPut(sid); return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(output)); } // get mounted device final Optional<DOMMountPoint> mountPoint = getMountPoint(inputData.getNode_name(), error); if (!mountPoint.isPresent()) { LOG.error(error); sid = "-1"; error = null; ContainerNode output = createCSOutPut(sid); return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(output)); } // get subscription id from subscription engine. sid = this.yangpushSubscriptionEngine.generateSubscriptionId(); inputData.setSubscription_id(sid); //Register notification listner if not done for the subscription //TODO: does it scale to handle mutiple push updates from a device for all subscriptions if (!this.notifyListnerRegister.containsKey(inputData.getNode_name())) { YangpushDOMNotificationListener listener = registerNotificationListnerPushUpdateForaNewDevice( mountPoint, inputData.getNode_name()); listener.insertSubscriptionId(inputData.getSubscription_id()); LOG.debug("New device being registered to listen PUSH-UPDATE notification."); } else { YangpushDOMNotificationListener listner = this.notifyListnerRegister.get(inputData.getNode_name()); listner.insertSubscriptionId(inputData.getSubscription_id()); LOG.debug("Device already registered to listen PUSH-UPDATE notification."); } // register notification listener for PUSH-UPDATE //BUG: NotificationListner should be one instance or multiple for a device?? /*YangpushDOMNotificationListener listener = new YangpushDOMNotificationListener(this.globalDomDataBroker); final Optional<DOMNotificationService> service = mountPoint.get().getService(DOMNotificationService.class); QName qname = PushUpdate.QNAME; SchemaPath schemaPath = SchemaPath.create(true, qname); @SuppressWarnings("unused") final ListenerRegistration<YangpushDOMNotificationListener> accessTopologyListenerListenerRegistration = service .get().registerNotificationListener(listener, schemaPath);*/ final Optional<DOMRpcService> rpcService = mountPoint.get().getService(DOMRpcService.class); QName uri = QName.create(NOTIFICATION_NS, NOTIFICATION_NS_DATE, "create-subscription"); SchemaPath type = SchemaPath.create(true, uri); ContainerNode cn = createDeviceCSRpcInput(inputData, error); CheckedFuture<DOMRpcResult, DOMRpcException> result = rpcService.get().invokeRpc(type, cn); ContainerNode output = createCSOutPut(sid); error = null; // update MD-SAL and subscription engine database this.yangpushSubscriptionEngine.updateSubscriptiontoMdSal(inputData.getSubscription_id(), inputData.getNode_name(), operations.create); return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(output)); }
From source file:org.opendaylight.netconf.sal.restconf.impl.RestconfImpl.java
private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC( final NormalizedNodeContext payload) { final ContainerNode value = (ContainerNode) payload.getData(); final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName(); final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier( QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path"))); final Object pathValue = path.isPresent() ? path.get().getValue() : null; if (!(pathValue instanceof YangInstanceIdentifier)) { final String errMsg = "Instance identifier was not normalized correctly "; LOG.debug(errMsg + rpcQName);/* w w w. j av a 2s . c o m*/ throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED); } final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue); String streamName = null; if (!pathIdentifier.isEmpty()) { final String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null); LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME); datastore = datastore == null ? DEFAULT_DATASTORE : datastore; DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME); scope = scope == null ? DEFAULT_SCOPE : scope; streamName = Notificator.createStreamNameFromUri( fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope); } if (Strings.isNullOrEmpty(streamName)) { final String errMsg = "Path is empty or contains value node which is not Container or List build-in type."; LOG.debug(errMsg + pathIdentifier); throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } final QName outputQname = QName.create(rpcQName, "output"); final QName streamNameQname = QName.create(rpcQName, "stream-name"); final ContainerNode output = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new NodeIdentifier(outputQname)) .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build(); if (!Notificator.existListenerFor(streamName)) { Notificator.createListener(pathIdentifier, streamName); } final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output); return Futures.immediateCheckedFuture(defaultDOMRpcResult); }
From source file:org.opendaylight.controller.sal.restconf.impl.RestconfImpl.java
private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC( final NormalizedNodeContext payload) { final ContainerNode value = (ContainerNode) payload.getData(); final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName(); final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier( QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path"))); final Object pathValue = path.isPresent() ? path.get().getValue() : null; if (!(pathValue instanceof YangInstanceIdentifier)) { final String errMsg = "Instance identifier was not normalized correctly "; LOG.debug(errMsg + rpcQName);/*from www . jav a2 s .co m*/ throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED); } final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue); String streamName = null; if (!pathIdentifier.isEmpty()) { final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null); LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME); datastore = datastore == null ? DEFAULT_DATASTORE : datastore; DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME); scope = scope == null ? DEFAULT_SCOPE : scope; streamName = Notificator.createStreamNameFromUri( fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope); } if (Strings.isNullOrEmpty(streamName)) { final String errMsg = "Path is empty or contains value node which is not Container or List build-in type."; LOG.debug(errMsg + pathIdentifier); throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } final RpcDefinition rpcSchemaNode = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode(); RestconfValidationUtils.checkDocumentedError(rpcSchemaNode != null, ErrorType.RPC, ErrorTag.INVALID_VALUE, "Create stream RPC output can not be null!"); final QName outputQname = rpcSchemaNode.getOutput().getQName(); final QName streamNameQname = QName.create(rpcQName, "stream-name"); final ContainerNode output = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new NodeIdentifier(outputQname)) .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build(); if (!Notificator.existListenerFor(streamName)) { Notificator.createListener(pathIdentifier, streamName); } final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output); return Futures.immediateCheckedFuture(defaultDOMRpcResult); }