/** * Test of synchronouslySendNotificationMessage method, of class PushManager. * * @throws Exception If an error occurs */ public void testSynchronouslySendNotificationMessage() throws Exception { final MockHelperNotificationEngine mockNotificationEngine = new MockHelperNotificationEngine() { @Override public void sendNotificationMessage( String username, String deviceId, Alert[] alerts, int uimode) throws NotificationNotSentException, NotificationException { incrementMessagesSent(); } public void validate() { assertEquals(1, totalMessageSent); } }; PushManager instance = new PushManager() { @Override protected NotificationEngine createNotificationEngine() { return mockNotificationEngine; } }; String username = "******"; String deviceId = "IMEI-1234567890"; Alert[] alerts = new Alert[] {new Alert()}; int uimode = 0; instance.synchronouslySendNotificationMessage(username, deviceId, alerts, uimode); mockNotificationEngine.validate(); }
/** * Test of asynchronouslySendNotificationMessages method, of class PushManager. * * @throws Exception If an error occurs */ public void testAsynchronouslySendNotificationMessages() throws Exception { final int sendingTimeSeconds = 2; final MockHelperNotificationEngine mockNotificationEngine = new MockHelperNotificationEngine() { @Override public void sendNotificationMessages(String username, Alert[] alerts, int uimode) throws NotificationNotSentException, NotificationException { idleFor(sendingTimeSeconds); incrementMessagesSent(); } public void validate() { assertEquals(1, totalMessageSent); } }; PushManager instance = new PushManager() { @Override protected NotificationEngine createNotificationEngine() { return mockNotificationEngine; } }; String username = "******"; Alert[] alerts = new Alert[] {new Alert()}; int uimode = 0; Future<?> future = instance.asynchronouslySendNotificationMessages(username, alerts, uimode); waitingDeliveryTermination(future, sendingTimeSeconds); mockNotificationEngine.validate(); }
/** * 使用APNS服务推送到苹果 * * @param product * @param cc * @param message */ public void push(Product product, Client cc, Payload message) { PushManager<SimpleApnsPushNotification> service = get(product); if (service != null) { try { if (StringUtils.isBlank(cc.getDeviceToken()) || "NULL".equalsIgnoreCase(cc.getDeviceToken())) { message.setStatus(cc.getUserId(), new PushStatus(PushStatus.NO_DEVICE_TOKEN)); } else { SimpleApnsPushNotification e = wrapPayload(cc, message); if (e == null) { message.setStatus(cc.getUserId(), new PushStatus(PushStatus.DeviceTokenInvalid)); } else { service.getQueue().put(e); message.setStatus(cc.getUserId(), new PushStatus(PushStatus.APNSSent)); ClientServiceImpl.instance.updateBadge(cc.getUserId(), 1); } } } catch (Exception e) { logger.error("Push Failed", e); message.setStatus(cc.getUserId(), new PushStatus(PushStatus.iOSPushError, e.getMessage())); } } else { logger.error("iOS Push Service Not Found."); message.setStatus(cc.getUserId(), new PushStatus(PushStatus.iOSPushConfigError)); } }
private void handleMessage(final Context context, Intent intent) { // push를 사용 안할 경우 메시지가 오더라도 무시 함. SharedPreferences preferences = context.getSharedPreferences("pushPref", Activity.MODE_PRIVATE); boolean isPushEnable = preferences.getBoolean("isPushEnable", true); if (!isPushEnable) { Logger.d("handleMessage", "isPushEnable : " + isPushEnable); return; } // 화면을 켬 pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock( PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb"); wl.acquire(); Log.i("handleMessage", "------------ COME MESSAGE: " + pushKey); // TODO Auto-generated method stub String count = intent.getExtras().getString("badge"); String message = intent.getExtras().getString("message"); // String collaspe_key = intent.getExtras().getString("collaspe_key"); Log.i("handleMessage", "------------ COME MESSAGE: " + message + ", " + count); Notification notification = new Notification( RUtil.getDrawableR(context, "app_icon"), message, System.currentTimeMillis()); // notiId int notiID = (int) System.currentTimeMillis(); // TODO 현재는 시작 화면으로 가게 했지만 추후 수정해야함. String title = PushManager.getInstance().getNotiMessage(PushManager.MESSAGE_TITLE); Intent in = new Intent(Intent.ACTION_MAIN); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); in.addCategory(Intent.CATEGORY_LAUNCHER); in.setComponent(new ComponentName(context, DummyActivity.class)); in.putExtra("push", message); in.putExtra("push_noti_id", notiID); PendingIntent pi = PendingIntent.getActivity( context, notiID, in, Intent.FLAG_ACTIVITY_NEW_TASK | PendingIntent.FLAG_ONE_SHOT); notification.setLatestEventInfo(context, title, message, pi); notification.flags |= Notification.FLAG_AUTO_CANCEL; // 선택시 자동삭제 NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); // 전체 제거 고려 if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) { notification.defaults |= android.app.Notification.DEFAULT_SOUND; } else { // 진동 효과 구성 long[] vibrate = {1000, 1000, 1000, 1000, 1000}; notification.vibrate = vibrate; } // nm.notify(PushManager.PUSH_MESSAGE, notification); nm.notify(notiID, notification); run.run(); }
/** * Test of asynchronouslySendNotificationMessage method, of class PushManager. The allowed threads * and the queue capacity is reached before the first request is fulfilled. The exceeding requests * are rejected by the MyRejectedExecutionHandler * * @throws Exception If an error occurs */ public void testAsynchronouslySendNotificationMessages_SmalQueue_SendMoreThanOneMessage() throws Exception { final int messagesToSend = 100; final int sendingTimeSeconds = 2; final int queueCapacity = 7; final int corePoolSize = 1; final int maximumPoolSize = 20; final MockHelperNotificationEngine mockNotificationEngine = new MockHelperNotificationEngine() { @Override public void sendNotificationMessages(String username, Alert[] alerts, int uimode) throws NotificationNotSentException, NotificationException { idleFor(sendingTimeSeconds); incrementMessagesSent(); } // the messages actually sent are equal to the sum of the // maximumPoolSize and the queueCapacity. All other messages // are discarded public void validate() { assertEquals(maximumPoolSize + queueCapacity, totalMessageSent); } }; PushManager instance = new PushManager() { @Override protected NotificationEngine createNotificationEngine() { return mockNotificationEngine; } }; instance.setCoreThreadPoolSize(corePoolSize); instance.setMaximumThreadPoolSize(maximumPoolSize); instance.setQueueCapacity(queueCapacity); instance.init(); int rejectedMessages = 0; Future<?>[] futures = new Future<?>[messagesToSend]; for (int i = 0; i < messagesToSend; ++i) { try { String username = "******"; Alert[] alerts = new Alert[] {new Alert()}; int uimode = 0; futures[i] = instance.asynchronouslySendNotificationMessages(username, alerts, uimode); } catch (RejectedExecutionException ex) { futures[i] = null; ++rejectedMessages; } } waitingDeliveryTermination(futures, sendingTimeSeconds); assertEquals(0, instance.getCurrentPushInProgressCount()); mockNotificationEngine.validate(); assertEquals(messagesToSend - maximumPoolSize - queueCapacity, rejectedMessages); }
public void handleMessage(Message msg) { String message = (String) msg.obj; if (PushManager.getInstance().getTerminate()) { final Activity ctx = (Activity) PushManager.getInstance().getContext(); if (ctx == null) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } else { new AlertDialog.Builder(ctx) .setCancelable(false) .setMessage(message) .setPositiveButton( "확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog1, int which) { dialog1.dismiss(); Smart2ProcessController controller = (Smart2ProcessController) ctx.getApplication(); Class activity = controller.getActivityClass(Smart2ProcessController.START_ACTIVITY); final Intent intent = new Intent(ctx, activity); intent.putExtra("Exit", true); intent.setFlags( Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); ctx.runOnUiThread( new Runnable() { @Override public void run() { ctx.startActivity(intent); ctx.overridePendingTransition( RUtil.getR(ctx, "anim", "zoom_enter"), RUtil.getR(ctx, "anim", "zoom_exit")); } }); } }) .create() .show(); } } else { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } }
@Override public void handleRejectedNotification( final PushManager<? extends SimpleApnsPushNotification> pushManager, final SimpleApnsPushNotification notification, final RejectedNotificationReason reason) { logger.error( "[%s] %s was rejected with rejection reason %s\n", pushManager.getName(), notification, reason); }
@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. } }
/** * Test of asynchronouslySendNotificationMessage method, of class PushManager. * * @throws Exception If an error occurs */ public void testAsynchronouslySendNotificationMessage_SendMoreThanOneMessage() throws Exception { final int messagesToSend = 100; final int sendingTimeSeconds = 2; final MockHelperNotificationEngine mockNotificationEngine = new MockHelperNotificationEngine() { @Override public void sendNotificationMessage( String username, String deviceId, Alert[] alerts, int uimode) throws NotificationNotSentException, NotificationException { idleFor(sendingTimeSeconds); incrementMessagesSent(); } public void validate() { assertEquals("All messages have to be sent", messagesToSend, totalMessageSent); } }; PushManager instance = new PushManager() { @Override protected NotificationEngine createNotificationEngine() { return mockNotificationEngine; } }; Future<?>[] futures = new Future<?>[messagesToSend]; for (int i = 0; i < messagesToSend; ++i) { String username = "******"; String deviceId = "IMEI-1234567890"; Alert[] alerts = new Alert[] {new Alert()}; int uimode = 0; futures[i] = instance.asynchronouslySendNotificationMessage(username, deviceId, alerts, uimode); } Thread.sleep(100); // the notification messages deliveries are just started so they are all in progress assertEquals( Math.min(instance.getCoreThreadPoolSize(), messagesToSend), instance.getCurrentPushInProgressCount()); assertEquals( Math.max(0, messagesToSend - instance.getCoreThreadPoolSize()), instance.getQueuedPushCount()); waitingDeliveryTermination(futures, sendingTimeSeconds); assertEquals(0, instance.getCurrentPushInProgressCount()); mockNotificationEngine.validate(); }
public void testAsynchronouslySendNotificationMessage_SmalQueue_SendLessThanTheCorePoolSize() throws Exception { // All messages are sent befor the first is fulfilled final int sendingTimeSeconds = 2; // the number of messages to send is greater than the corePoolSize but // less than the corePoolSize plus the queueCapacity so no new threads // are added final int messagesToSend = 8; final int queueCapacity = 10; final int corePoolSize = 10; final int maximumPoolSize = 30; final MockHelperNotificationEngine mockNotificationEngine = new MockHelperNotificationEngine() { @Override public void sendNotificationMessage( String username, String deviceId, Alert[] alerts, int uimode) throws NotificationNotSentException, NotificationException { idleFor(sendingTimeSeconds); incrementMessagesSent(); } // the messages actually sent are equal to the sum of the // maximumPoolSize and the queueCapacity. All other messages // are discarded public void validate() { assertEquals( Math.min(messagesToSend, maximumPoolSize + queueCapacity), totalMessageSent); } }; PushManager instance = new PushManager() { @Override protected NotificationEngine createNotificationEngine() { return mockNotificationEngine; } }; instance.setCoreThreadPoolSize(corePoolSize); instance.setMaximumThreadPoolSize(maximumPoolSize); instance.setQueueCapacity(queueCapacity); instance.init(); int rejectedMessages = 0; Future<?>[] futures = new Future<?>[messagesToSend]; for (int i = 0; i < messagesToSend; ++i) { try { String username = "******"; String deviceId = "IMEI-1234567890"; Alert[] alerts = new Alert[] {new Alert()}; int uimode = 0; futures[i] = instance.asynchronouslySendNotificationMessage(username, deviceId, alerts, uimode); } catch (RejectedExecutionException ex) { futures[i] = null; ++rejectedMessages; } } waitingDeliveryTermination(futures, sendingTimeSeconds); assertEquals(0, instance.getCurrentPushInProgressCount()); mockNotificationEngine.validate(); assertEquals(Math.max(0, messagesToSend - maximumPoolSize - queueCapacity), rejectedMessages); // every new message to send increase the number of threads until the // corePoolSize is reached. // every message exceeding the corePoolSize is enqueued until the // queueCapacity is reached. // int numThreads = Math.max( Math.min(corePoolSize, messagesToSend), Math.min(maximumPoolSize, messagesToSend - queueCapacity)); assertEquals(numThreads, instance.getThreadPoolSize()); assertEquals(messagesToSend, numThreads); }
private void handleRegistration(final Context context, final Intent intent) { // TODO Auto-generated method stub String registration_id = null; if (intent.getStringExtra("error") != null) { Log.i("intent", intent.toString()); Log.i("errLog", intent.getStringExtra("error")); Log.i("handleRegistration", "@@@ Registration failed @@@"); String error = intent.getStringExtra("error"); if (error.equals("SERVICE_NOT_AVAILABLE")) { error = "서비스가 불가능한 상태입니다.\n네트워크 연결을 확인해 주세요."; } else if (error.equals("ACCOUNT_MISSING")) { error = "단말기에 Google 계정을 등록해주세요."; } else if (error.equals("AUTHENTICATION_FAILED")) { error = "Google 계정 인증 실패입니다."; } else if (error.equals("TOO_MANY_REGISTRATIONS")) { error = "단말기에 Push 서비스를 이용하는 어플리케이션이 너무 많아 더이상 등록이 불가능 합니다."; } else if (error.equals("INVALID_SENDER")) { error = "Push Google 계정을 확인해주세요."; } else if (error.equals("PHONE_REGISTRATION_ERROR")) { error = "Push 서비스를 지원하지 않는 단말기입니다."; } String message = "C2DM 단말기 등록 오류\n" + error; // Toast.makeText(context, message , Toast.LENGTH_LONG).show(); Message msg = new Message(); msg.what = ERROR_C2DM; msg.obj = message; handler.sendMessage(msg); } else if (intent.getStringExtra("unregistered") != null) { Log.i("handleRegistration", "@@@ unregistration done @@@"); PushManager.getInstance() .pushNoti(context, PushManager.getInstance().getNotiMessage(PushManager.MESSAGE_STOP)); SharedPreferences preferences = context.getSharedPreferences("pushPref", Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString("registration_id", ""); editor.commit(); Logger.d("PushReceiver", preferences.getString("registration_id", "")); } else if (intent.getStringExtra("registration_id") != null) { registration_id = intent.getStringExtra("registration_id"); Log.i("handleRegistration", "@@@ registration_id: " + registration_id); /////////////////////////////////////////////////////////// pushKey = registration_id; Thread t = new Thread( new Runnable() { @Override public void run() { try { SharedPreferences preferences = context.getSharedPreferences("pushPref", Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString("registration_id", pushKey); editor.commit(); PushManager.getInstance().registDevice(context, pushKey); } catch (final Exception e) { e.printStackTrace(); Message msg = new Message(); msg.what = ERROR_PUSHSERVER; msg.obj = e.getMessage(); handler.sendMessage(msg); } } }); t.start(); } }
public PushManager get(Product product) { if (StringUtils.isBlank(product.getDevCertPath()) || StringUtils.isBlank(product.getDevCertPass()) || StringUtils.isBlank(product.getCertPath()) || StringUtils.isBlank(product.getCertPass())) { logger.error("Product iOS Push Service Miss Cert Path and Password. {}", product); return null; } PushManager service = mapping.get(product.getId()); if (service == null) { ApnsEnvironment apnsEnvironment = null; SSLContext sslContext = null; try { if (sandBox) { apnsEnvironment = ApnsEnvironment.getSandboxEnvironment(); sslContext = SSLContextUtil.createDefaultSSLContext( product.getDevCertPath(), product.getDevCertPass()); } else { apnsEnvironment = ApnsEnvironment.getProductionEnvironment(); sslContext = SSLContextUtil.createDefaultSSLContext(product.getCertPath(), product.getCertPass()); } } catch (KeyStoreException e) { logger.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); } catch (CertificateException e) { logger.error(e.getMessage(), e); } catch (UnrecoverableKeyException e) { logger.error(e.getMessage(), e); } catch (KeyManagementException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } PushManagerConfiguration configuration = new PushManagerConfiguration(); configuration.setConcurrentConnectionCount(1); final PushManager<SimpleApnsPushNotification> pushManager = new PushManager<SimpleApnsPushNotification>( apnsEnvironment, sslContext, null, // Optional: custom event loop group null, // Optional: custom ExecutorService for calling listeners null, // Optional: custom BlockingQueue implementation configuration, "ApnsPushManager-" + product.getId()); pushManager.registerRejectedNotificationListener(new PushRejectedNotificationListener()); pushManager.registerFailedConnectionListener(new PushFailedConnectionListener()); pushManager.start(); // ApnsServiceBuilder builder = APNS.newService(); // if (sandBox){ // builder.withCert(product.getDevCertPath(), product.getDevCertPass()); // builder.withSandboxDestination(); // }else{ // builder.withCert(product.getCertPath(), product.getCertPass()); // builder.withProductionDestination(); // } // service = // builder.asPool(10).withCacheLength(Integer.MAX_VALUE).withDelegate(delegateAdapter).asQueued().build(); mapping.put(product.getId(), pushManager); service = pushManager; } return service; }