Example usage for io.netty.util.concurrent Future isSuccess

List of usage examples for io.netty.util.concurrent Future isSuccess

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:de.unipassau.isl.evs.ssh.app.handler.AppModifyModuleHandler.java

License:Open Source License

/**
 * Removes the given module. Invoker of this method can be notified with a NewModuleListener
 * when this action finished.//w  w  w.  j a v  a 2s. c  o  m
 *
 * @param module the module to remove
 */
public void removeModule(Module module) {
    ModifyModulePayload payload = new ModifyModulePayload(module);
    final Future<Void> future = newResponseFuture(
            sendMessageToMaster(MASTER_MODULE_REMOVE, new Message(payload)));
    future.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            fireUnregistrationFinished(future.isSuccess());
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppRegisterNewDeviceHandler.java

License:Open Source License

/**
 * Sends a request message for a token to the master. {@code requestToken()} does not return a Future like other
 * functions that are sending messages. Use the {@code RegisterNewDeviceListener} to get notified when a reply
 * message is handled by this handler./*from   w  w w. j  ava2  s  .  c  o m*/
 *
 * @param user the user who is registered
 */
public void requestToken(UserDevice user) {
    Message message = new Message(new GenerateNewRegisterTokenPayload(null, user));
    final Future<GenerateNewRegisterTokenPayload> future = newResponseFuture(
            sendMessageToMaster(MASTER_USER_REGISTER, message));
    future.addListener(new FutureListener<GenerateNewRegisterTokenPayload>() {
        @Override
        public void operationComplete(Future<GenerateNewRegisterTokenPayload> future) throws Exception {
            if (future.isSuccess()) {
                handleUserRegisterResponse(future.get());
            } else {
                fireTokenError();
            }
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppSlaveManagementHandler.java

License:Open Source License

/**
 * Sends a message to master to registers a new slave.
 *
 * @param slaveID                  the device ID of the new slave
 * @param slaveName                the name of the new slave
 * @param passiveRegistrationToken the passive Registration token
 *//* w  w  w .  java2s  .c  o  m*/
public void registerNewSlave(DeviceID slaveID, String slaveName, byte[] passiveRegistrationToken) {
    RegisterSlavePayload payload = new RegisterSlavePayload(slaveName, slaveID, passiveRegistrationToken);
    final Future<Void> future = newResponseFuture(
            sendMessageToMaster(MASTER_SLAVE_REGISTER, new Message(payload)));
    future.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            fireSlaveRegistered(future.isSuccess());
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppSlaveManagementHandler.java

License:Open Source License

/**
 * Sends a message to master to delete the given slave.
 *
 * @param slaveID the slave to delete/*from w ww . j av  a  2  s .  co  m*/
 */
public void deleteSlave(DeviceID slaveID) {
    DeleteDevicePayload payload = new DeleteDevicePayload(slaveID);
    final Future<Void> future = newResponseFuture(
            sendMessageToMaster(MASTER_SLAVE_DELETE, new Message(payload)));
    future.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            fireSlaveRemoved(future.isSuccess());
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppUserConfigurationHandler.java

License:Open Source License

private void sendUserConfigMessage(Message message, RoutingKey<? extends MessagePayload> key,
        final UserConfigurationEvent.EventType eventType) {
    final Future<Void> future = newResponseFuture(sendMessageToMaster(key, message));
    future.addListener(new FutureListener<Void>() {
        @Override//from  w w  w. jav a2  s. c o  m
        public void operationComplete(Future<Void> future) throws Exception {
            final boolean success = future.isSuccess();
            fireUserInfoUpdated(new UserConfigurationEvent(eventType, success));
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.core.messaging.OutgoingRouter.java

License:Open Source License

private Message.AddressedMessage sendMessage(DeviceID toID, String routingKey, Message msg, boolean log) {
    final Message.AddressedMessage amsg = msg.setDestination(getOwnID(), toID, routingKey);
    final Future<Void> future = doSendMessage(amsg);
    amsg.setSendFuture(future);// ww  w. j a va2s.  c  o m
    if (log) {
        future.addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                if (future.isSuccess()) {
                    Log.v(TAG, "SENT " + amsg);
                } else {
                    Log.w(TAG, "Could not send Message " + amsg + " because of "
                            + Log.getStackTraceString(future.cause()));
                }
            }
        });
    }
    final AccessLogger logger = getComponent(AccessLogger.KEY);
    if (logger != null) {
        logger.logAccess(RoutingKey.forMessage(amsg));
    }
    return amsg;
}

From source file:de.unipassau.isl.evs.ssh.core.messaging.OutgoingRouter.java

License:Open Source License

/**
 * Sends a reply message to the device the original message came from.
 * Also sets the {@link Message#HEADER_REFERENCES_ID} of the sent message to the sequence number of the original message.
 *
 * @see #sendMessage(DeviceID, String, Message)
 *//*w ww  .  j a v a 2  s .co m*/
public Message.AddressedMessage sendReply(Message.AddressedMessage original, Message reply) {
    reply.putHeader(Message.HEADER_REFERENCES_ID, original.getSequenceNr());
    final Message.AddressedMessage amsg = sendMessage(original.getFromID(),
            RoutingKey.getReplyKey(original.getRoutingKey()), reply, !CoreConstants.TRACK_STATISTICS // don't use the default logger if TRACK_STATISTICS is set
    );
    if (CoreConstants.TRACK_STATISTICS) {
        final long originalTimestamp = original.getHeader(Message.HEADER_TIMESTAMP);
        amsg.getSendFuture().addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                final long replyTimestamp = amsg.getHeader(Message.HEADER_TIMESTAMP);
                final long replyTime = replyTimestamp - originalTimestamp;
                final long sendTime = System.currentTimeMillis() - replyTimestamp;
                final long overallTime = replyTime + sendTime;
                if (future.isSuccess()) {
                    Log.v(TAG,
                            "SENT " + amsg + " after " + replyTime + "+" + sendTime + "=" + overallTime + "ms");
                } else {
                    Log.w(TAG, "Could not send Message " + amsg + " because of "
                            + Log.getStackTraceString(future.cause()));
                }
            }
        });
    }
    return amsg;
}

From source file:de.unipassau.isl.evs.ssh.core.network.Client.java

License:Open Source License

/**
 * Initializes the netty client and tries to connect to the server.
 *//*from  www.  j a  va 2  s. co  m*/
protected synchronized void initClient() {
    Log.d(TAG, "initClient");
    if (!isActive) {
        Log.w(TAG, "Not starting Client that has been explicitly shut-down");
        return;
    }
    if (isChannelOpen()) {
        Log.w(TAG, "Not starting Client that is already connected");
        return;
    } else {
        // Close channels open from previous connections
        if (channelFuture != null && channelFuture.channel() != null) {
            Log.v(TAG, "Cleaning up " + (channelFuture.channel().isOpen() ? "open" : "closed")
                    + " Channel from previous connection attempt");
            channelFuture.channel().close();
        }
        // Clean-up the closed channel as it is no longer needed
        channelFuture = null;
    }

    // And queue the (re-)connect
    final Future<?> future = requireComponent(ExecutionServiceComponent.KEY).submit(new Runnable() {
        @Override
        public void run() {
            attemptConnectClient();
        }
    });
    future.addListener(new FutureListener<Object>() {
        @Override
        public void operationComplete(Future future) throws Exception {
            if (!future.isSuccess()) {
                Log.w(TAG, "Could not schedule connect to master", future.cause());
            }
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.core.network.UDPDiscoveryClient.java

License:Open Source License

/**
 * Schedule the next run of {@link #sendDiscoveryRequest()} if it hasn't been scheduled yet.
 *
 * @return the Future returned by {@link io.netty.channel.EventLoop#schedule(Callable, long, TimeUnit)}
 *///from   w ww  .  jav  a2  s . c om
private synchronized ScheduledFuture<?> scheduleDiscoveryRetry() {
    Log.v(TAG, "scheduleDiscoveryRetry()");
    // don't schedule a second execution if one is already pending
    final boolean isExecutionPending = retryFuture != null && !retryFuture.isDone();
    if (isDiscoveryRunning && !isExecutionPending) {
        if (requireComponent(Client.KEY).isChannelOpen() && timeout == 0) {
            Log.d(TAG,
                    "scheduleDiscoveryRetry() running indefinitely, but Client Channel is open. Was stopDiscovery called?");
        }
        retryFuture = requireComponent(ExecutionServiceComponent.KEY).schedule(new Runnable() {
            @Override
            public void run() {
                if (timeout > 0 && System.currentTimeMillis() > timeout) {
                    Log.i(TAG, "Stopping discovery after timeout");
                    stopDiscovery();
                }
                if (isDiscoveryRunning) {
                    sendDiscoveryRequest();
                    /* Mark this future as completed, so that the next discovery request will be scheduled.
                     * Otherwise retryFuture.isDone() would be false until this method terminates and the following
                     * recursive call wouldn't schedule the next execution. */
                    retryFuture = null;
                    scheduleDiscoveryRetry();
                }
            }
        }, CLIENT_MILLIS_BETWEEN_BROADCASTS, TimeUnit.MILLISECONDS);
        retryFuture.addListener(new FutureListener<Object>() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (!future.isSuccess()) {
                    Log.w(TAG, "Could not reschedule execution of UDP discovery", future.cause());
                }
            }
        });
    } else {
        Log.d(TAG, "not scheduling another retry because " + "isDiscoveryRunning = " + isDiscoveryRunning
                + ", retryFuture = " + retryFuture);
    }
    return retryFuture;
}

From source file:de.unipassau.isl.evs.ssh.slave.handler.SlaveDoorHandler.java

License:Open Source License

private void handleUnlatchDoor(final DoorPayload payload, final Message.AddressedMessage message) {
    Key<DoorBuzzer> key = new Key<>(DoorBuzzer.class, payload.getModuleName());
    requireComponent(key).unlock(7000).addListener(new FutureListener<Void>() {
        @Override/*  w  w w . j  a  va2s  .  c  o m*/
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isSuccess()) {
                sendReply(message, new Message(new DoorPayload(payload.getModuleName())));
            } else {
                sendReply(message, new Message(new ErrorPayload(future.cause())));
            }
        }
    });
}