void disconnect() { apnsClient.disconnect(); }
public void handleConnectionClosure(ApnsConnection<SimpleApnsPushNotification> connection) { try { connection.waitForPendingWritesToFinish(); } catch (InterruptedException ignored) { } this.connectionClosed = true; latch.countDown(); }
private static ApnsEnvironment getApnsEnvironment(Notifier notifier){ return notifier.isProduction() ? ApnsEnvironment.getProductionEnvironment() : ApnsEnvironment.getSandboxEnvironment(); } private static SSLContext getSSLContext(Notifier notifier) {
RetryingApnsClient(String apnCertificate, String apnKey, int retryCount) throws IOException { MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME); DropwizardApnsClientMetricsListener metricsListener = new DropwizardApnsClientMetricsListener(); for (Map.Entry<String, Metric> entry : metricsListener.getMetrics().entrySet()) { metricRegistry.register(name(getClass(), entry.getKey()), entry.getValue()); } this.apnsClient = new ApnsClientBuilder().setClientCredentials(initializeCertificate(apnCertificate), initializePrivateKey(apnKey), null) .setMetricsListener(metricsListener) .build(); this.retryExecutor = initializeExecutor(retryCount); }
List<SimpleApnsPushNotification> notifications = new ArrayList<SimpleApnsPushNotification>(); if (cause instanceof SSLException || cause instanceof SSLHandshakeException || cause instanceof ClosedChannelException) { //cert is probably bad so shut it down. if (!pushManager.isShutDown()) { pushManager.unregisterFailedConnectionListener(this); BlockingQueue notificationQueue = pushManager.getQueue(); if(notificationQueue !=null){ LinkedBlockingQueue<SimpleApnsPushNotification> queue = ( LinkedBlockingQueue<SimpleApnsPushNotification> )notificationQueue; pushManager.shutdown(); } catch (InterruptedException ie) { logger.error("Failed to stop push services", ie); pushManager.getQueue().clear();
@Override public ApnsClientHandler build(final Http2ConnectionDecoder decoder, final Http2ConnectionEncoder encoder, final Http2Settings initialSettings) { Objects.requireNonNull(this.authority(), "Authority must be set before building an ApnsClientHandler."); final ApnsClientHandler handler = new ApnsClientHandler(decoder, encoder, initialSettings, this.apnsClient(), this.authority(), this.useTokenAuthentication()); this.frameListener(handler.new ApnsClientHandlerFrameAdapter()); return handler; }
@Override public ListenableFuture<ApnResult> call(RetryContext context) throws Exception { SettableFuture<ApnResult> result = SettableFuture.create(); SimpleApnsPushNotification notification = new SimpleApnsPushNotification(apnId, topic, payload, expiration, DeliveryPriority.IMMEDIATE); apnsClient.sendNotification(notification).addListener(new ResponseHandler(apnsClient, result)); return result; } });
@Override public void operationComplete(io.netty.util.concurrent.Future<PushNotificationResponse<SimpleApnsPushNotification>> result) { try { PushNotificationResponse<SimpleApnsPushNotification> response = result.get(); if (response.isAccepted()) { future.set(new ApnResult(ApnResult.Status.SUCCESS, null)); } else if ("Unregistered".equals(response.getRejectionReason())) { future.set(new ApnResult(ApnResult.Status.NO_SUCH_USER, response.getRejectionReason())); } else { logger.warn("Got APN failure: " + response.getRejectionReason()); future.set(new ApnResult(ApnResult.Status.GENERIC_FAILURE, response.getRejectionReason())); } } catch (InterruptedException e) { future.setException(e); } catch (ExecutionException e) { if (e.getCause() instanceof ClientNotConnectedException) setDisconnected(e.getCause()); else future.setException(e.getCause()); } }
@Override public MockApnsServerHandler build(final Http2ConnectionDecoder decoder, final Http2ConnectionEncoder encoder, final Http2Settings initialSettings) { final MockApnsServerHandler handler = new MockApnsServerHandler(decoder, encoder, initialSettings, this.apnsServer(), this.useTokenAuthentication(), this.baseTopicFromCertificate()); this.frameListener(handler); return handler; }
private EntityPushManager getPushManager(Notifier notifier) throws ExecutionException { if (pushManager == null || !pushManager.isStarted() || pushManager.isShutDown()) { PushManagerConfiguration config = new PushManagerConfiguration(); config.setConcurrentConnectionCount(Runtime.getRuntime().availableProcessors() * 2); queue = new ArrayBlockingQueue<>(10000); pushManager = new EntityPushManager(notifier, entityManager, queue, config); //only tested when a message is sent pushManager.registerRejectedNotificationListener(new RejectedAPNsListener()); //this will get tested when start is called pushManager.registerFailedConnectionListener(new FailedConnectionListener()); //unregistered expired devices pushManager.registerExpiredTokenListener(new ExpiredTokenListener()); try { if (!pushManager.isStarted()) { //ensure manager is started pushManager.start(); } } catch (IllegalStateException ise) { logger.warn("getPushManager: failed to start", ise);//could have failed because its started } } return pushManager; }
void connect(boolean sandbox) { apnsClient.connect(sandbox ? ApnsClient.DEVELOPMENT_APNS_HOST : ApnsClient.PRODUCTION_APNS_HOST).awaitUninterruptibly(); }
private void setDisconnected(final Throwable t) { logger.warn("Client disconnected, waiting for reconnect...", t); client.getReconnectionFuture().addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> complete) { logger.warn("Client reconnected..."); future.setException(t); } }); } }
@Override public void handleExpiredTokens(PushManager<? extends SimpleApnsPushNotification> pushManager, Collection<ExpiredToken> expiredTokens) { Map<String,Date> inactiveDeviceMap = new HashMap<>(); for(ExpiredToken token : expiredTokens){ String expiredToken = new String(token.getToken()); inactiveDeviceMap.put(expiredToken, token.getExpiration()); } if(pushManager instanceof EntityPushManager){ EntityPushManager entityPushManager = (EntityPushManager) pushManager; InactiveDeviceManager inactiveDeviceManager = new InactiveDeviceManager(entityPushManager.getNotifier(),entityPushManager.getEntityManager()); inactiveDeviceManager.removeInactiveDevices(inactiveDeviceMap); } } }
/** * mark message failed * * @throws Exception */ public void messageSendFailed(RejectedNotificationReason reason) throws Exception { if (tracker != null) { tracker.failed(reason.name(), "Failed sending notification."); } }
@Override public void removeInactiveDevices() throws Exception { PushManager<SimpleApnsPushNotification> pushManager = getPushManager(notifier); pushManager.requestExpiredTokens(); }
/** * Sets the metrics listener for this client. Metrics listeners gather information that describes the performance * and behavior of a client, and are completely optional. * * @param metricsListener the metrics listener for this client, or {@code null} if this client should not report * metrics to a listener * * @since 0.6 */ protected void setMetricsListener(final ApnsClientMetricsListener metricsListener) { this.metricsListener = metricsListener != null ? metricsListener : new NoopMetricsListener(); }
@Override public void onHeadersRead(final ChannelHandlerContext ctx, final int streamId, final Http2Headers headers, final int streamDependency, final short weight, final boolean exclusive, final int padding, final boolean endOfStream) throws Http2Exception { this.onHeadersRead(ctx, streamId, headers, padding, endOfStream); }
@Override public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers, final int streamDependency, final short weight, final boolean exclusive, final int padding, final boolean endOfStream) throws Http2Exception { this.onHeadersRead(context, streamId, headers, padding, endOfStream); }
protected AuthenticationTokenSupplier getAuthenticationTokenSupplierForTopic(final String topic) throws NoKeyForTopicException { final AuthenticationTokenSupplier supplier = this.authenticationTokenSuppliersByTopic.get(topic); if (supplier == null) { throw new NoKeyForTopicException("No signing key found for topic " + topic); } return supplier; }
@Override public void handleFailedConnection( final PushManager<? extends SimpleApnsPushNotification> pushManager, final Throwable cause) { logger.error(pushManager.getName() + " failed to connect Apple APNS server. ", cause); if (cause instanceof SSLHandshakeException) { // This is probably a permanent failure, and we should shut down // the PushManager. } } }