List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:com.newlandframework.avatarmq.broker.LauncherListener.java
License:Apache License
public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoke.setReason(future.cause()); }// w w w . j a v a 2s . c om }
From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java
License:Apache License
public void sendAsynMessage(RequestMessage request, final NotifyCallback listener) { Channel channel = factory.getMessageChannel(); if (channel == null) { return;/*from w w w. j a v a 2 s . com*/ } Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap(); CallBackInvoker<Object> invoker = new CallBackInvoker<Object>(); callBackMap.put(request.getMsgId(), invoker); invoker.setRequestId(request.getMsgId()); invoker.join(new CallBackListener<Object>() { public void onCallBack(Object t) { ResponseMessage response = (ResponseMessage) t; listener.onEvent((ProducerAckMessage) response.getMsgParams()); } }); ChannelFuture channelFuture = channel.writeAndFlush(request); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoker.setReason(future.cause()); } } }); }
From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java
License:Apache License
public Object sendAsynMessage(RequestMessage request) { Channel channel = factory.getMessageChannel(); if (channel == null) { return null; }//from www .j av a 2 s . co m Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap(); CallBackInvoker<Object> invoker = new CallBackInvoker<Object>(); callBackMap.put(request.getMsgId(), invoker); invoker.setRequestId(request.getMsgId()); ChannelFuture channelFuture = channel.writeAndFlush(request); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoker.setReason(future.cause()); } } }); try { Object result = invoker.getMessageResult(factory.getTimeOut(), TimeUnit.MILLISECONDS); callBackMap.remove(request.getMsgId()); return result; } catch (RuntimeException e) { e.printStackTrace(); return null; } }
From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java
License:Apache License
public void sendSyncMessage(RequestMessage request) { Channel channel = factory.getMessageChannel(); if (channel == null) { return;//from w ww . j a v a2s .c o m } Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap(); CallBackInvoker<Object> invoker = new CallBackInvoker<Object>(); callBackMap.put(request.getMsgId(), invoker); invoker.setRequestId(request.getMsgId()); ChannelFuture channelFuture; try { channelFuture = channel.writeAndFlush(request).sync(); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoker.setReason(future.cause()); } } }); } catch (InterruptedException ex) { Logger.getLogger(MessageProcessor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.ning.http.client.providers.netty_4.NettyConnectListener.java
License:Apache License
public final void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { Channel channel = f.channel(); channel.pipeline().context(NettyAsyncHttpProvider.class).attr(NettyAsyncHttpProvider.DEFAULT_ATTRIBUTE) .set(future);//from w w w . ja v a 2 s . c om SslHandler sslHandler = (SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER); if (!handshakeDone.getAndSet(true) && (sslHandler != null)) { ((SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER)).handshake() .addListener(this); return; } HostnameVerifier v = config.getHostnameVerifier(); if (sslHandler != null) { if (!v.verify(future.getURI().getHost(), sslHandler.engine().getSession())) { ConnectException exception = new ConnectException("HostnameVerifier exception."); future.abort(exception); throw exception; } } future.provider().writeRequest(f.channel(), config, future, nettyRequest); } else { Throwable cause = f.cause(); logger.debug("Trying to recover a dead cached channel {} with a retry value of {} ", f.channel(), future.canRetry()); if (future.canRetry() && cause != null && (NettyAsyncHttpProvider.abortOnDisconnectException(cause) || ClosedChannelException.class.isAssignableFrom(cause.getClass()) || future.getState() != NettyResponseFuture.STATE.NEW)) { logger.debug("Retrying {} ", nettyRequest); if (future.provider().remotelyClosed(f.channel(), future)) { return; } } logger.debug("Failed to recover from exception: {} with channel {}", cause, f.channel()); boolean printCause = f.cause() != null && cause.getMessage() != null; ConnectException e = new ConnectException( printCause ? cause.getMessage() + " to " + future.getURI().toString() : future.getURI().toString()); if (cause != null) { e.initCause(cause); } future.abort(e); } }
From source file:com.nitesh.netty.snoop.client.HttpSnoopClient.java
License:Apache License
private void sendRequest() { // Prepare the HTTP request. FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());/*from w w w. j a v a 2s . c om*/ //HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { System.out.println("Request sent. Success? " + future.isSuccess()); if (!future.isSuccess()) { future.cause().printStackTrace(System.out); } } }); }
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
/** * <p>Connects to the given APNs gateway on the given port.</p> * * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param host the APNs gateway to which to connect * @param port the port on which to connect to the APNs gateway * * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send * push notifications//from w w w.j a v a2 s . c om * * @see ApnsClient#PRODUCTION_APNS_HOST * @see ApnsClient#DEVELOPMENT_APNS_HOST * @see ApnsClient#DEFAULT_APNS_PORT * @see ApnsClient#ALTERNATE_APNS_PORT * * @since 0.5 */ public Future<Void> connect(final String host, final int port) { final Future<Void> connectionReadyFuture; if (this.bootstrap.config().group().isShuttingDown() || this.bootstrap.config().group().isShutdown()) { connectionReadyFuture = new FailedFuture<>(GlobalEventExecutor.INSTANCE, new IllegalStateException( "Client's event loop group has been shut down and cannot be restarted.")); } else { synchronized (this.bootstrap) { // We only want to begin a connection attempt if one is not already in progress or complete; if we already // have a connection future, just return the existing promise. if (this.connectionReadyPromise == null) { this.metricsListener.handleConnectionAttemptStarted(this); final ChannelFuture connectFuture = this.bootstrap.connect(host, port); this.connectionReadyPromise = connectFuture.channel().newPromise(); connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { // This may seem spurious, but our goal here is to accurately report the cause of // connection failure; if we just wait for connection closure, we won't be able to // tell callers anything more specific about what went wrong. connectionReadyPromise.tryFailure(future.cause()); } } } }); connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.connectionReadyPromise != null) { // We always want to try to fail the "connection ready" promise if the connection // closes; if it has already succeeded, this will have no effect. ApnsClient.this.connectionReadyPromise.tryFailure(new IllegalStateException( "Channel closed before HTTP/2 preface completed.")); ApnsClient.this.connectionReadyPromise = null; } if (ApnsClient.this.reconnectionPromise != null) { log.debug("Disconnected. Next automatic reconnection attempt in {} seconds.", ApnsClient.this.reconnectDelaySeconds); ApnsClient.this.scheduledReconnectFuture = future.channel().eventLoop() .schedule(new Runnable() { @Override public void run() { log.debug("Attempting to reconnect."); ApnsClient.this.connect(host, port); } }, ApnsClient.this.reconnectDelaySeconds, TimeUnit.SECONDS); ApnsClient.this.reconnectDelaySeconds = Math.min( ApnsClient.this.reconnectDelaySeconds, MAX_RECONNECT_DELAY_SECONDS); } } } }); this.connectionReadyPromise.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.reconnectionPromise != null) { log.info("Connection to {} restored.", future.channel().remoteAddress()); ApnsClient.this.reconnectionPromise.trySuccess(); } else { log.info("Connected to {}.", future.channel().remoteAddress()); } ApnsClient.this.reconnectDelaySeconds = INITIAL_RECONNECT_DELAY_SECONDS; ApnsClient.this.reconnectionPromise = future.channel().newPromise(); } ApnsClient.this.metricsListener.handleConnectionAttemptSucceeded(ApnsClient.this); } else { log.info("Failed to connect.", future.cause()); ApnsClient.this.metricsListener.handleConnectionAttemptFailed(ApnsClient.this); } } }); } connectionReadyFuture = this.connectionReadyPromise; } } return connectionReadyFuture; }
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
/** * <p>Sends a push notification to the APNs gateway.</p> * * <p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the * gateway. If the notification was accepted, it may be delivered to its destination device at some time in the * future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers * should <em>not</em> attempt to re-send the notification.</p> * * <p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to * <em>send</em> a notification to the gatewayi.e. those that fail with exceptionsshould generally be considered * non-permanent, and callers should attempt to re-send the notification when the underlying problem has been * resolved.</p>//from w w w . j a va 2 s . com * * <p>In particular, attempts to send a notification when the client is not connected will fail with a * {@link ClientNotConnectedException}. If the client was previously connected and has not been explicitly * disconnected (via the {@link ApnsClient#disconnect()} method), the client will attempt to reconnect * automatically. Callers may wait for a reconnection attempt to complete by waiting for the {@code Future} returned * by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param notification the notification to send to the APNs gateway * * @param <T> the type of notification to be sent * * @return a {@code Future} that will complete when the notification has been either accepted or rejected by the * APNs gateway * * @since 0.8 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends ApnsPushNotification> Future<PushNotificationResponse<T>> sendNotification( final T notification) { final Future<PushNotificationResponse<T>> responseFuture; final long notificationId = this.nextNotificationId.getAndIncrement(); // Instead of synchronizing here, we keep a final reference to the connection ready promise. We can get away // with this because we're not changing the state of the connection or its promises. Keeping a reference ensures // we won't suddenly "lose" the channel and get a NullPointerException, but risks sending a notification after // things have shut down. In that case, though, the returned futures should fail quickly, and the benefit of // not synchronizing for every write seems worth it. final ChannelPromise connectionReadyPromise = this.connectionReadyPromise; if (connectionReadyPromise != null && connectionReadyPromise.isSuccess() && connectionReadyPromise.channel().isActive()) { final Channel channel = connectionReadyPromise.channel(); final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = new DefaultPromise( channel.eventLoop()); channel.writeAndFlush(new PushNotificationAndResponsePromise(notification, responsePromise)) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId); } else { responsePromise.tryFailure(future.cause()); } } }); responseFuture = (Future) responsePromise; } else { log.debug("Failed to send push notification because client is not connected: {}", notification); responseFuture = new FailedFuture<>(GlobalEventExecutor.INSTANCE, NOT_CONNECTED_EXCEPTION); } responseFuture.addListener(new GenericFutureListener<Future<PushNotificationResponse<T>>>() { @Override public void operationComplete(final Future<PushNotificationResponse<T>> future) throws Exception { if (future.isSuccess()) { final PushNotificationResponse<T> response = future.getNow(); if (response.isAccepted()) { ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId); } else { ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId); } } else { ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId); } } }); return responseFuture; }
From source file:com.relayrides.pushy.apns.ApnsClientHandler.java
License:Open Source License
@Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception { if (event instanceof IdleStateEvent) { assert PING_TIMEOUT < ApnsClient.PING_IDLE_TIME_MILLIS; log.trace("Sending ping due to inactivity."); final ByteBuf pingDataBuffer = context.alloc().ioBuffer(8, 8); pingDataBuffer.writeLong(this.nextPingId++); this.encoder().writePing(context, false, pingDataBuffer, context.newPromise()) .addListener(new GenericFutureListener<ChannelFuture>() { @Override//from w w w. j av a2 s. co m public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { ApnsClientHandler.this.pingTimeoutFuture = future.channel().eventLoop() .schedule(new Runnable() { @Override public void run() { log.debug("Closing channel due to ping timeout."); future.channel().close(); } }, PING_TIMEOUT, TimeUnit.SECONDS); } else { log.debug("Failed to write PING frame.", future.cause()); future.channel().close(); } } }); this.flush(context); } super.userEventTriggered(context, event); }
From source file:com.relayrides.pushy.apns.ApnsClientThread.java
License:Open Source License
private void sendNextNotification(final long timeout, final TimeUnit timeUnit) throws InterruptedException { final T notification = this.pushManager.getQueue().poll(timeout, timeUnit); if (this.isInterrupted()) { this.pushManager.enqueuePushNotification(notification); } else if (notification != null) { final SendableApnsPushNotification<T> sendableNotification = new SendableApnsPushNotification<T>( notification, this.sequenceNumber++); final String threadName = this.getName(); if (log.isTraceEnabled()) { log.trace(String.format("%s sending %s", threadName, sendableNotification)); }/* w ww .j a v a 2 s .c o m*/ this.sentNotificationBuffer.addSentNotification(sendableNotification); this.channel.write(sendableNotification).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(final ChannelFuture future) { if (future.cause() != null) { if (log.isTraceEnabled()) { log.trace(String.format("%s failed to write notification %s", threadName, sendableNotification), future.cause()); } requestReconnection(); // Delivery failed for some IO-related reason; re-enqueue for another attempt, but // only if the notification is in the sent notification buffer (i.e. if it hasn't // been re-enqueued for another reason). final T failedNotification = sentNotificationBuffer .getAndRemoveNotificationWithSequenceNumber( sendableNotification.getSequenceNumber()); if (failedNotification != null) { pushManager.enqueuePushNotification(failedNotification); } } else { if (log.isTraceEnabled()) { log.trace(String.format("%s successfully wrote notification %d", threadName, sendableNotification.getSequenceNumber())); } } } }); this.hasEverSentNotification = true; if (++this.writesSinceLastFlush >= ApnsClientThread.BATCH_SIZE) { this.channel.flush(); this.writesSinceLastFlush = 0; } } else { if (this.writesSinceLastFlush > 0) { this.channel.flush(); this.writesSinceLastFlush = 0; } } }