Example usage for com.google.common.util.concurrent SettableFuture get

List of usage examples for com.google.common.util.concurrent SettableFuture get

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture get.

Prototype

@Override
    public V get() throws InterruptedException, ExecutionException 

Source Link

Usage

From source file:org.opendaylight.usc.plugin.UscExceptionHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, UscException ex) throws Exception {
    log.trace("UscExceptionHandler channelRead0" + ex);

    final Throwable t = ex.getCause();
    Channel channel = ctx.channel();
    UscRouteIdentifier routeId = ctx.channel().attr(UscPlugin.ROUTE_IDENTIFIER).get();
    if (routeId != null) {
        // this is a channel using remote channel
        if (broker == null) {
            broker = UscServiceUtils.getService(UscRouteBrokerService.class);
        }/*from   w w  w. jav a2s .c o  m*/
        if (broker != null) {
            broker.removeLocalSession(routeId);
        } else {
            log.error(
                    "Broker service is null! Can't check if it is remote channel message, failed to proccess this exception {}.",
                    ex);
        }
        return;
    }
    SettableFuture<UscSessionImpl> tmp = channel.attr(UscPlugin.SESSION).get();
    if (tmp != null) {
        UscSessionImpl session = tmp.get();
        UscChannelImpl connection = session.getChannel();

        // connection is down
        if (t instanceof UscConnectionException) {
            plugin.getConnectionManager().removeConnection(connection);
        } else if (t instanceof UscChannelException) {
            // TODO
            ;
        } else if (t instanceof UscSessionException) {
            connection.removeSession(session.getSessionId());
        }
    }

    throw ex;
}

From source file:com.griddynamics.jagger.coordinator.http.server.CoordinatorAdapter.java

private AbstractProxyWorker createProxyWorker(final Set<Qualifier<Command<Serializable>>> qualifiers) {
    return new AbstractProxyWorker(qualifiers) {

        @Override/*w ww.  j  a v  a 2s .  com*/
        protected Serializable handleCommand(Command<Serializable> command, NodeContext nodeContext) {
            log.debug("Handling command {} for node {}", command, nodeContext);
            AsyncRunner<Command<Serializable>, Serializable> packExchanger = exchangers
                    .get(nodeContext.getId());
            FutureAsyncCallback<Serializable> callback = FutureAsyncCallback.create();
            packExchanger.run(command, callback);

            SettableFuture<Serializable> future = callback.getFuture();
            try {
                log.debug("Waiting for command completion");
                return future.get();
            } catch (InterruptedException e) {
                throw Throwables.propagate(e);
            } catch (ExecutionException e) {
                throw Throwables.propagate(e);
            }
        }
    };
}

From source file:io.v.syncbase.Syncbase.java

/**
 * Scans the neighborhood for nearby users.
 *
 * @param cb The callback to call when a User is found or lost.
 *//* w w w  . ja  v  a2  s  .  c  o  m*/
public static void addScanForUsersInNeighborhood(final ScanNeighborhoodForUsersCallback cb) {
    synchronized (sScanMappingMu) {
        try {
            long scanId = Neighborhood.NewScan(new Neighborhood.NeighborhoodScanCallbacks() {
                @Override
                public void onPeer(final NeighborhoodPeer peer) {
                    final SettableFuture<Boolean> setFuture = SettableFuture.create();
                    Syncbase.sOpts.mCallbackExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            User u = new User(getAliasFromBlessingPattern(peer.blessings));
                            if (peer.isLost) {
                                cb.onLost(u);
                            } else {
                                cb.onFound(u);
                            }
                            setFuture.set(true);
                        }
                    });
                    try {
                        setFuture.get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                        System.err.println(e.toString());
                    }
                }
            });
            sScanMapping.put(cb, scanId);
        } catch (VError vError) {
            cb.onError(vError);
        }
    }
}

From source file:se.sics.dozy.DozySyncComp.java

@Override
public <E extends KompicsEvent & Identifiable> DozyResult sendReq(E req, long timeout) {
    SettableFuture<DozyResult> futureResult = SettableFuture.create();
    trigger(new DozySyncEvent(req, futureResult, timeout), selfPort.getPair());
    DozyResult result;//from  ww  w  . j  av a 2  s.com
    try {
        result = futureResult.get();
    } catch (InterruptedException ex) {
        result = DozyResult.internalError("dozy problem");
    } catch (ExecutionException ex) {
        result = DozyResult.internalError("dozy problem");
    }
    return result;
}

From source file:org.opendaylight.usc.plugin.UscDemultiplexer.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, UscFrame frame) throws Exception {
    LOG.trace("UscDemultiplexer.channelRead: " + frame);

    if (frame instanceof UscControl) {
        UscControl controlMsg = (UscControl) frame;
        if (controlMsg.getControlCode() == UscControl.ControlCode.ECHO) {
            SocketAddress remoteAddress = ctx.channel().remoteAddress();
            promiseMap.get(remoteAddress).set(new Throwable("Success"));
            LOG.trace("channelRead0: promiseMap = " + promiseMap);
            return;
        }//from w  w  w.j av a  2  s. c om
    }

    final UscHeader header = frame.getHeader();
    final int sessionId = header.getSessionId();
    final UscChannelImpl connection = ctx.channel().attr(UscPlugin.CHANNEL).get();

    final UscSessionImpl session = connection.getSession(sessionId);
    final LocalChannel serverChannel = session.getServerChannel();
    if (frame instanceof UscError) {
        // propagate exception to the client channel
        UscSessionException ex = new UscSessionException(((UscError) frame).getErrorCode());

        serverChannel.writeAndFlush(ex);
        plugin.sendEvent(new UscSessionErrorEvent(session, ex));
    } else if (frame instanceof UscData) {

        if (serverChannel != null) {
            LOG.trace("write session " + sessionId + " to " + serverChannel + ": " + frame.getPayload());

            ByteBuf payload = frame.getPayload();

            plugin.sendEvent(new UscSessionTransactionEvent(session, payload.readableBytes(), 0));

            serverChannel.writeAndFlush(payload);
        } else {
            UscChannelException ex = new UscChannelException(
                    "write unknown session " + sessionId + "; discard");
            plugin.sendEvent(new UscChannelErrorEvent(session.getChannel(), ex));

            throw ex;
        }
    } else if (frame instanceof UscControl) {
        UscControl controlMsg = (UscControl) frame;
        Channel clientChannel = serverChannel.attr(UscPlugin.CLIENT_CHANNEL).get();
        if (controlMsg.getControlCode() == UscControl.ControlCode.TERMINATION_REQUEST) {
            LOG.trace("UscDemultiplexer received control message TERMINATION_REQUEST");
            clientChannel.close();

            // send back TERMINATION_RESPONSE
            UscControl data = new UscControl(session.getPort(), session.getSessionId(), 2);
            ctx.channel().writeAndFlush(data);
        } else if (controlMsg.getControlCode() == UscControl.ControlCode.TERMINATION_RESPONSE) {
            LOG.trace("UscDemultiplexer received control message TERMINATION_RESPONSE");
            if (clientChannel != null) {
                SettableFuture<Boolean> status = plugin.getCloseFuture().get(clientChannel);
                status.set(true);
                LOG.trace("UscDemultiplexer: termination status is " + status.get());
            }
        }
    } else {
        LOG.trace("UscDemultiplexer.channelRead: unexpected UscFrame object " + frame);
        UscChannelException ex = new UscChannelException("unexpected UscFrame object " + frame);
        plugin.sendEvent(new UscChannelErrorEvent(session.getChannel(), ex));

        throw ex;
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private static void uploadBlob(List<TestCase> tests, String blobAccessToken) {
    String urlBlob = "https://daylight.blob.core.windows.net/attachments";

    for (TestCase test : tests) {
        String blobName = test.getFileName();
        String body = test.getLog();

        URI requestUrl = null;/* www  .  ja  v  a2 s  . c o m*/

        try {
            requestUrl = new URI(urlBlob + "/" + blobName + "?" + blobAccessToken);
        } catch (URISyntaxException e) {
        }

        test.setFileName(blobName);

        HttpPut request = new HttpPut(requestUrl);
        request.addHeader("x-ms-blob-type", "BlockBlob");

        try {
            request.setEntity(new StringEntity(body, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
        }

        final SettableFuture<Void> externalFuture = SettableFuture.create();

        ListenableFuture<HttpURLConnection> internalFuture = execute(request);

        Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
            @Override
            public void onFailure(Throwable throwable) {
                externalFuture.setException(throwable);
            }

            @Override
            public void onSuccess(HttpURLConnection connection) {
                try {
                    connection.getInputStream();
                    externalFuture.set(null);
                } catch (Throwable throwable) {
                    externalFuture.setException(throwable);
                }
            }
        });

        try {
            externalFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.opendaylight.usc.agent.UscAgentUdpHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, UscFrame frame) throws Exception {

    final UscHeader header = frame.getHeader();

    final int sessionId = header.getSessionId();
    final int port = header.getApplicationPort();

    Channel client = clients.get(sessionId);
    if (frame instanceof UscData) {
        if (client == null) {
            try {
                client = cb.connect(InetAddress.getLoopbackAddress(), port).sync().channel();
                client.attr(SESSION_ID).set(sessionId);
                client.attr(PORT).set(port);
                clients.put(sessionId, client);
            } catch (Exception e) {
                if (e instanceof ConnectException) {
                    UscError reply = new UscError(port, sessionId, UscError.ErrorCode.ECONNREFUSED.getCode());
                    plugin.writeAndFlush(reply);
                } else if (e instanceof PortUnreachableException) {
                    UscError reply = new UscError(port, sessionId, UscError.ErrorCode.ENETUNREACH.getCode());
                    plugin.writeAndFlush(reply);
                } else {
                    UscError reply = new UscError(port, sessionId, UscError.ErrorCode.E_OTHER.getCode());
                    plugin.writeAndFlush(reply);
                    throw e;
                }/*  w  w  w .  j av a2s.  c  o  m*/
            }
        }
        if (client != null) {
            client.writeAndFlush(frame.getPayload());
        }
    } else if (frame instanceof UscControl) {
        UscControl control = (UscControl) frame;

        // close it
        if (control.getControlCode() == UscControl.ControlCode.TERMINATION_REQUEST) {
            if (client != null) {
                client.close();
                clients.remove(sessionId);
            }

            // send back the response
            UscControl data = new UscControl(port, sessionId,
                    UscControl.ControlCode.TERMINATION_RESPONSE.getCode());
            plugin.writeAndFlush(data);
            LOG.trace("UscAgentUdpHandler send TERMINATION_RESPONSE");
        } else if (control.getControlCode() == UscControl.ControlCode.TERMINATION_RESPONSE) {
            LOG.trace("UscAgentUdpHandler received control message TERMINATION_RESPONSE, port#: " + port
                    + " ,session#: " + sessionId);
            SettableFuture<Boolean> status = agent.getCloseFuture().get(sessionId);
            status.set(true);

            try {
                LOG.trace("UscAgentUdp termination status: " + status.get());
            } catch (Exception e) {
                ;
            }
        } else if (control.getControlCode() == UscControl.ControlCode.ECHO) {
            // send back the response
            UscControl data = new UscControl(port, sessionId, UscControl.ControlCode.ECHO.getCode());
            plugin.writeAndFlush(data);
            LOG.trace("UscAgentUdpHandler send ECHO back.");
        }
    }

}

From source file:org.apache.beam.runners.dataflow.worker.MetricTrackingWindmillServerStub.java

public Windmill.KeyedGetDataResponse getStateData(String computation, Windmill.KeyedGetDataRequest request) {
    gcThrashingMonitor.waitForResources("GetStateData");
    activeStateReads.getAndIncrement();//from  ww  w  .  j  ava 2  s  . co m

    try {
        if (useStreamingRequests) {
            GetDataStream stream = streamPool.getStream();
            try {
                return stream.requestKeyedData(computation, request);
            } finally {
                streamPool.releaseStream(stream);
            }
        } else {
            SettableFuture<Windmill.KeyedGetDataResponse> response = SettableFuture.create();
            readQueue.add(new QueueEntry(computation, request, response));
            return response.get();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        activeStateReads.getAndDecrement();
    }
}

From source file:org.opendaylight.usc.agent.UscAgentTcpHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, UscFrame frame) throws InterruptedException {

    final UscHeader header = frame.getHeader();

    final int sessionId = header.getSessionId();
    final int port = header.getApplicationPort();

    Channel client = clients.get(sessionId);
    if (frame instanceof UscData) {
        LOG.trace("UscAgentTcpHandler: read uscData " + frame.toString());
        System.out.println("UscAgentTcpHandler: read uscData " + frame.toString());
        if (client == null) {
            try {
                client = cb.connect(InetAddress.getLoopbackAddress(), port).sync().channel();
                client.attr(SESSION_ID).set(sessionId);
                client.attr(PORT).set(port);
                clients.put(sessionId, client);
            } catch (Exception e) {
                if (e instanceof ConnectException) {
                    UscError reply = new UscError(port, sessionId, UscError.ErrorCode.ECONNREFUSED.getCode());
                    plugin.writeAndFlush(reply);
                } else if (e instanceof PortUnreachableException) {
                    UscError reply = new UscError(port, sessionId, UscError.ErrorCode.ENETUNREACH.getCode());
                    plugin.writeAndFlush(reply);
                } else {
                    UscError reply = new UscError(port, sessionId, UscError.ErrorCode.E_OTHER.getCode());
                    plugin.writeAndFlush(reply);
                    throw e;
                }// ww w .j a  va2 s . co m
            }
        }
        if (client != null) {
            client.writeAndFlush(frame.getPayload());
        }
    } else if (frame instanceof UscControl) {
        UscControl control = (UscControl) frame;
        LOG.trace("UscAgentTcpHandler: read UscControl " + control.toString());
        System.out.println("UscAgentTcpHandler: read UscControl " + control.toString());
        // close it
        if (control.getControlCode() == UscControl.ControlCode.TERMINATION_REQUEST) {
            if (client != null) {
                client.close();
                clients.remove(sessionId);
            }

            // send back the response
            UscControl data = new UscControl(port, sessionId,
                    UscControl.ControlCode.TERMINATION_RESPONSE.getCode());
            plugin.writeAndFlush(data);
            LOG.trace("UscAgentTcpHandler send TERMINATION_RESPONSE");
            System.out.println("UscAgentTcpHandler send TERMINATION_RESPONSE");
        } else if (control.getControlCode() == UscControl.ControlCode.TERMINATION_RESPONSE) {
            LOG.trace("UscAgentTcp received control message TERMINATION_RESPONSE, port#: " + port
                    + " ,session#: " + sessionId);
            System.out.println("UscAgentTcp received control message TERMINATION_RESPONSE, port#: " + port
                    + " ,session#: " + sessionId);
            SettableFuture<Boolean> status = agent.getCloseFuture().get(sessionId);
            status.set(true);

            try {
                LOG.trace("UscAgentTcp termination status: " + status.get());
                System.out.println("UscAgentTcp termination status: " + status.get());
            } catch (Exception e) {
                ;
            }
        } else if (control.getControlCode() == UscControl.ControlCode.ECHO) {
            // send back the response
            UscControl data = new UscControl(port, sessionId, UscControl.ControlCode.ECHO.getCode());
            plugin.writeAndFlush(data);
            LOG.trace("UscAgentUdpHandler send ECHO back.");
        }
    }
}

From source file:org.apache.beam.sdk.runners.inprocess.InProcessSideInputContainer.java

/**
 * Set the value of the {@link PCollectionView} in the {@link BoundedWindow} to be based on the
 * specified values, if the values are part of a later pane than currently exist within the
 * {@link PCollectionViewWindow}.// www  . j ava 2s .  com
 */
private void updatePCollectionViewWindowValues(PCollectionView<?> view, BoundedWindow window,
        Collection<WindowedValue<?>> windowValues) {
    PCollectionViewWindow<?> windowedView = PCollectionViewWindow.of(view, window);
    SettableFuture<Iterable<? extends WindowedValue<?>>> future = null;
    try {
        future = viewByWindows.get(windowedView);
        if (future.isDone()) {
            Iterator<? extends WindowedValue<?>> existingValues = future.get().iterator();
            PaneInfo newPane = windowValues.iterator().next().getPane();
            // The current value may have no elements, if no elements were produced for the window,
            // but we are recieving late data.
            if (!existingValues.hasNext() || newPane.getIndex() > existingValues.next().getPane().getIndex()) {
                viewByWindows.invalidate(windowedView);
                viewByWindows.get(windowedView).set(windowValues);
            }
        } else {
            future.set(windowValues);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (future != null && !future.isDone()) {
            future.set(Collections.<WindowedValue<?>>emptyList());
        }
    } catch (ExecutionException e) {
        Throwables.propagate(e.getCause());
    }
}