target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void intentService_onHandleIntent_doesNotStartForegroundActivityWhenInForeground() { when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(false); getSubject().onHandleIntent(intent); verify(context, never()).startActivity(any(Intent.class)); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void context_functions_getSelectedNotificationData() { byte[] data = {}; PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(ExtensionUtils.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationData()).thenReturn(data); when(ExtensionUtils.getFreObject(data)).thenReturn(freObject); assertSame(freObject, callFunction("getSelectedNotificationData")); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_getSelectedNotificationCode() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationCode()).thenReturn("Code"); try { when(FREObject.newObject("Code")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationCode")); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_getSelectedActionId() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getActionId()).thenReturn("ActionId"); try { when(FREObject.newObject("ActionId")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationAction")); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_getSelectedUserResponse() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getUserResponse()).thenReturn("User Response"); try { when(FREObject.newObject("User Response")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationUserResponse")); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_checkForNotificationAction_whenCacheWasUpdated() { byte data[] = {}; LocalNotificationCache.getInstance().reset(); LocalNotificationCache.getInstance().setData("MyCode", data, "actionId", "User Response"); callFunction("checkForNotificationAction"); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_checkForNotificationAction_whenCacheWasNotUpdated() { LocalNotificationCache.getInstance().reset(); callFunction("checkForNotificationAction"); verify(getSubject(), never()).dispatchStatusEventAsync("notificationSelected", "status"); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_checkForNotificationAction_dispatchesOnlyOnce() { byte data[] = {}; LocalNotificationCache.getInstance().reset(); LocalNotificationCache.getInstance().setData("MyCode", data, "actionId", "User Response"); callFunction("checkForNotificationAction"); callFunction("checkForNotificationAction"); verify(getSubject(), times(1)).dispatchStatusEventAsync("notificationSelected", "status"); }
|
static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_cancel() { try { when(arg1.getAsString()).thenReturn("MyID"); } catch (Throwable e) { e.printStackTrace(); } callFunction("cancel"); verify(manager).cancel("MyID"); verify(persistenceManager).removeNotification("MyID"); }
|
private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); }
|
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } }
|
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } }
|
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_cancelAll() { callFunction("cancelAll"); verify(manager).cancelAll(); verify(persistenceManager).clearNotifications(); }
|
private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); }
|
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } }
|
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } }
|
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_activate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(false); callFunction("activate"); assertTrue(ApplicationStatus.getInForeground()); }
|
private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void intentService_onHandleIntent_startsForegroundActivityWhenNotInForeground_andNotActive() { when(ApplicationStatus.getActive()).thenReturn(false); when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getStringExtra(Constants.MAIN_ACTIVITY_CLASS_NAME_KEY)).thenReturn("MainActivityClass"); getSubject().onHandleIntent(intent); verify(intent).setClassName(context, "MainActivityClass"); verify(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); verify(intent).putExtra(Constants.BACKGROUND_MODE_KEY, false); verify(context).startActivity(intent); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void context_functions_deactivate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(true); callFunction("deactivate"); assertFalse(ApplicationStatus.getInForeground()); }
|
private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_activate() { ApplicationStatus.setInForeground(false); callFunction("activate"); assertFalse(ApplicationStatus.getInForeground()); }
|
private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void context_functions_deactivate() { ApplicationStatus.setInForeground(true); callFunction("deactivate"); assertTrue(ApplicationStatus.getInForeground()); }
|
private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); }
|
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }
|
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); assertCache(); }
|
boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelectedEvent(); }
|
boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsInBackground() { ApplicationStatus.setInForeground(true); ApplicationStatus.setInForeground(false); getSubject().dispatchWhenInForeground(); assertCache(); }
|
boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsInBackground() { ApplicationStatus.reset(); getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelectedEvent(); }
|
boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsInForeground() { ApplicationStatus.setInForeground(true); getSubject().dispatchWhenInForeground(); assertCache(); }
|
boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
@Test public void dispatcher_dispatchInForeground_dispatchesIfAppIsInForeground() { ApplicationStatus.setInForeground(true); getSubject().dispatchWhenInForeground(); verify(context).dispatchNotificationSelectedEvent(); }
|
boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }
|
@Test public void notificationTimeInterval_yearInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 365, getSubject(LocalNotificationTimeInterval.YEAR_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void intentService_onHandleIntent_startsForegroundActivityWhenNotInForeground_andActive() { when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getStringExtra(Constants.MAIN_ACTIVITY_CLASS_NAME_KEY)).thenReturn("MainActivityClass"); getSubject().onHandleIntent(intent); verify(intent).setClassName(context, "MainActivityClass"); verify(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); verify(intent).putExtra(Constants.BACKGROUND_MODE_KEY, false); verify(context).startActivity(intent); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void notificationTimeInterval_monthInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 30, getSubject(LocalNotificationTimeInterval.MONTH_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_dayInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60 * 24, getSubject(LocalNotificationTimeInterval.DAY_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_hourInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60, getSubject(LocalNotificationTimeInterval.HOUR_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_minuteInterval_toMilliseconds() { assertEquals( 1000 * 60, getSubject(LocalNotificationTimeInterval.MINUTE_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_secondInterval_toMilliseconds() { assertEquals( 1000, getSubject(LocalNotificationTimeInterval.SECOND_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_weekInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60 * 24 * 7, getSubject(LocalNotificationTimeInterval.WEEK_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_quarterInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 91, getSubject(LocalNotificationTimeInterval.QUARTER_CALENDAR_UNIT).toMilliseconds() ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_unkownIntervalInterval_returnsZeroMilliseconds() { assertEquals(0, getSubject(1 << 20).toMilliseconds()); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void notificationTimeInterval_toMillisecondsWithParameter_multipliesIntervalByParameter() { assertEquals( 4000, getSubject(LocalNotificationTimeInterval.SECOND_CALENDAR_UNIT).toMilliseconds(4) ); }
|
public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); }
|
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }
|
@Test public void provider_onReceive_doesNothing_ifNotRightPermission() { when(intent.getAction()).thenReturn("any.other.permission"); getSubject().onReceive(context, intent); verify(persistenceManager, never()).readNotificationKeys(); }
|
@Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }
|
@Test public void intentService_onHandleIntent_doesNotStartBackgroundActivityWhenInForeground() { when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onHandleIntent(intent); verify(context, never()).startActivity(any(Intent.class)); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void provider_onReceive_notifiesEventsInTheFuture() { initNotifications(); getSubject().onReceive(context, intent); verify(notificationManager).notify(notification1); }
|
@Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }
|
@Test public void provider_onReceive_removesEventsInThePast() { initNotifications(); getSubject().onReceive(context, intent); verify(persistenceManager).removeNotification("NOTIF2"); }
|
@Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }
|
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }
|
@Test public void service_onReceive_startsService() { getSubject().onReceive(context, intent); verify(notificationIntent).setClass(context, LocalNotificationIntentService.class); verify(context).startService(notificationIntent); }
|
@SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
@Test public void service_onReceive_tonesDownNotificationService() { getSubject().onReceive(context, intent); verify(notificationIntent).putExtra(Constants.VIBRATE, false); verify(notificationIntent).putExtra(Constants.PLAY_SOUND, false); verify(notificationIntent).putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT); }
|
@SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
@Test public void service_onReceive_mergesIntentIntoNotificationIntent() { getSubject().onReceive(context, intent); verify(notificationIntent).putExtras(bundle); }
|
@SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
@Test public void service_onReceive_onLessThanNougat_doesNotMergeIntentIntoNotificationIntent() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N - 1); getSubject().onReceive(context, intent); verify(notificationIntent, never()).putExtra(eq(Constants.USER_RESPONSE_KEY), anyString()); }
|
@SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
@Test public void service_onReceive_noNougatOrHigher_mergesUserResponseIntoNotificationIntent() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N); Bundle resultsBundle = mock(Bundle.class); PowerMockito.mockStatic(RemoteInput.class); when(RemoteInput.getResultsFromIntent(intent)).thenReturn(resultsBundle); when(resultsBundle.getString(Constants.USER_RESPONSE_KEY)).thenReturn("User Response"); getSubject().onReceive(context, intent); verify(notificationIntent).putExtra(Constants.USER_RESPONSE_KEY, "User Response"); }
|
@SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }
|
@Test public void callbacks_setAppInForeground_whenActivityStarted() { ApplicationStatus.setInForeground(false); getSubject().onActivityStarted(null); assertTrue(ApplicationStatus.getInForeground()); }
|
@Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
@Test public void callbacks_setAppInForeground_whenActivityStopped() { ApplicationStatus.setInForeground(true); getSubject().onActivityStopped(null); assertFalse(ApplicationStatus.getInForeground()); }
|
@Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
@Test public void callbacks_doesNothing_whenNullIntent() { when(activity.getIntent()).thenReturn(null); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
|
@Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
@Test public void intentService_onHandleIntent_doesNotStartBackgroundActivityWhenNotInForeground_andActive() { when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onHandleIntent(intent); verify(context, never()).startActivity(any(Intent.class)); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void callbacks_doesNothing_whenNotInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(false); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
|
@Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
@Test public void callbacks_hideActivity_whenInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onActivityCreated(activity, null); verify(activity).moveTaskToBack(true); }
|
@Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }
|
@Test public void manager_notify_notifiesOnce_whenIntervalIsZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = 0; getSubject().notify(notification); verify(notifier).notify(100L, pendingIntent, notification); }
|
void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
@Test public void manager_notify_notifiesRepeating_whenIntervalIsNonZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = LocalNotificationTimeInterval.MINUTE_CALENDAR_UNIT; getSubject().notify(notification); verify(notifier).notifyRepeating(100L, notification.getRepeatIntervalMilliseconds(), pendingIntent, notification); }
|
void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
@Test public void manager_notify_calculatesNextTriggerTimeBasedOnCurrentDate() { when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); Date date = mock(Date.class); try { PowerMockito .whenNew(Date.class) .withNoArguments() .thenReturn(date); PowerMockito.whenNew(NextNotificationCalculator.class) .withArguments(notification) .thenReturn(calculator); } catch (Throwable e) { e.printStackTrace(); } LocalNotification notification = getNotification(); getSubject().notify(notification); verify(calculator).getTime(date); }
|
void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
@Test public void manager_notify_setsUpIntent() { getSubject().notify(getNotification()); verify(intentFactory).createIntent(notification); }
|
void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }
|
@Test public void manager_cancel_cancelsAllStoredAlarms() { when(PendingIntent.getBroadcast(context, "notif1".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); getSubject().cancel("notif1"); verify(intent).setAction("notif1"); verify(alarmManager).cancel(pendingIntent); }
|
void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } }
|
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } } }
|
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } } LocalNotificationManager(Context context); }
|
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } } LocalNotificationManager(Context context); }
|
@Test public void dispatcher_dispatch_whenAppIsInForeground_andNormalNotification_doesNotDisplayNotification() { getSubject().dispatch(); verify(notificationManager).notify("testCode", Constants.STANDARD_NOTIFICATION_ID, notification); }
|
void dispatch() { dispatchNotification(); }
|
NotificationDispatcher { void dispatch() { dispatchNotification(); } }
|
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); }
|
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); }
|
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); }
|
@Test public void intentService_onReceiveWhenAppIsInForeground_andNormalNotification_doesNotDispatchNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); getSubject().onReceive(context, intent); verify(notificationDispatcher, never()).dispatch(); }
|
@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
@Test public void intentService_onReceiveWhenAppIsNotInForeground_andNormalNotification_dispatchesNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(false); mockNotificationDispatch(); getSubject().onReceive(context, intent); verify(notificationDispatcher).dispatch(); }
|
@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
@Test public void intentService_onHandleIntent_startsBackgroundActivityWhenNotInForeground_andNotActive() { when(ApplicationStatus.getActive()).thenReturn(false); when(ApplicationStatus.getInForeground()).thenReturn(false); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); when(intent.getStringExtra(Constants.MAIN_ACTIVITY_CLASS_NAME_KEY)).thenReturn("MainActivityClass"); getSubject().onHandleIntent(intent); verify(intent).setClassName(context, "MainActivityClass"); verify(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); verify(intent).putExtra(Constants.BACKGROUND_MODE_KEY, true); verify(context).startActivity(intent); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void intentService_onReceiveWhenNotificationShowsInForeground_dispatchesNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); when(bundle.getBoolean(Constants.SHOW_IN_FOREGROUND)).thenReturn(true); mockNotificationDispatch(); getSubject().onReceive(context, intent); verify(notificationDispatcher).dispatch(); verify(eventDispatcher, never()).dispatchWhenInForeground(); }
|
@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
@Test public void intentService_onReceiveWhenNotification_doesNotTriggersNewNotification_whenIntervalNotSent() { mockNotificationDispatch(); try { PowerMockito.whenNew(LocalNotificationManager.class).withArguments(context) .thenReturn(notificationManager); } catch(Throwable e) { e.printStackTrace(); } getSubject().onReceive(context, intent); verify(notificationManager, never()).notify(any(LocalNotification.class)); }
|
@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
@Test public void intentService_onReceiveWhenNotification_triggersNewNotification_whenIntervalSent() { when(bundle.getInt(Constants.REPEAT_INTERVAL, 0)).thenReturn(1); mockNotificationDispatch(); try { PowerMockito.whenNew(LocalNotificationManager.class).withArguments(context) .thenReturn(notificationManager); PowerMockito.whenNew(PersistenceManager.class).withArguments(context) .thenReturn(persistenceManager); } catch(Throwable e) { e.printStackTrace(); } LocalNotification notification = new LocalNotification(); when(persistenceManager.readNotification("KeyCode")).thenReturn(notification); getSubject().onReceive(context, intent); verify(notificationManager).notify(notification); }
|
@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }
|
@Test public void provider_attachInfo_updatesAuthority() { assertEquals("expected.authority", NotificationSoundProvider.AUTHORITY); getSubject().attachInfo(null, info); assertEquals("new.authority", NotificationSoundProvider.AUTHORITY); }
|
@Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }
|
@Test public void provider_attachInfo_updatesUri() { assertEquals("content: getSubject().attachInfo(null, info); assertEquals("content: }
|
@Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); }
|
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }
|
@Test public void provider_openAssetFile_returnsNullIfNotMp3OrWav() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.wav"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.any"); try { assertNull(getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } }
|
@Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }
|
@Test public void provider_openAssetFile_decompressesUriLastSegment() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { getSubject().openAssetFile(uri, ""); verify(decompressor).decompress("sound.mp3"); } catch (FileNotFoundException e) { e.printStackTrace(); } }
|
@Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); }
|
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }
|
@Test public void settings_getSoundUri_returnsUriIfBundlePlaysSoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); NotificationSoundProvider.CONTENT_URI = "content: assertNotNull(getSubject().getSoundUri()); verifyStatic(Uri.class); Uri.parse("content: }
|
public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }
|
@Test public void settings_getSoundUri_returnsNullIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertNull(getSubject().getSoundUri()); when(bundle.getString(Constants.SOUND_NAME)).thenReturn(""); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertNull(getSubject().getSoundUri()); }
|
public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }
|
@Test public void settings_getSoundUri_returnsNullIfBundleDoesNotPlaySoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); assertNull(getSubject().getSoundUri()); }
|
public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }
|
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }
|
@Test public void intentService_onHandleIntent_dispatchesNotificationWhenUserResponsePresent() { when(intent.getStringExtra(Constants.USER_RESPONSE_KEY)).thenReturn("User Response"); getSubject().onHandleIntent(intent); verify(notificationDispatcher).dispatch(); }
|
@Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
LocalNotificationIntentService extends IntentService { @Override public final void onHandleIntent(Intent intent) { boolean backgroundMode = intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false); sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); tryEventDispatch(intent); handleResponse(intent); logStatus(intent); Logger.log("Background mode: " + backgroundMode); if(backgroundMode) { if (!ApplicationStatus.getActive()) openActivityInBackground(intent); } else if (!ApplicationStatus.getInForeground()) { openActivityInForeground(intent); } } LocalNotificationIntentService(); @Override final void onHandleIntent(Intent intent); }
|
@Test public void testWinOrLose() { Map<Integer, Long[]> mapIO = new HashMap<Integer, Long[]>() {{ put(0, new Long[]{new Long("2"), new Long("3")}); put(1, new Long[]{new Long("5"), new Long("3")}); }}; for (Map.Entry<Integer, Long[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose.winOrLose(io.getValue()[0], io.getValue()[1]) ); } }
|
public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; }
|
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } }
|
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } }
|
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int winOrLose(long first, long second); }
|
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int winOrLose(long first, long second); }
|
@Test public void testHello() { String ret = helloBean.sayHello(); Assertions.assertNotNull(ret); System.out.println(ret); }
|
@Deprecated public String sayHello() { return "Hello world!"; }
|
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } }
|
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); }
|
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }
|
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }
|
@Test public void testValue() { String ret = helloBean.osName; Assertions.assertNotNull(ret); System.out.println(String.format("osName:%s, resource: %s", helloBean.osName, helloBean.url.toString() )); }
|
@Override public String toString() { return "HelloBean says hello world!"; }
|
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } }
|
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); }
|
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }
|
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }
|
@Test public void testHello() { Object ret = helloController.hello("test", null, null); Assertions.assertTrue(ret.toString().contains("test")); System.out.println(ret); }
|
@ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; }
|
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; } }
|
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; } }
|
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; } @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender); }
|
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; } @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender); }
|
@Test public void testServerUrl() { String ret = serverConfig.getServerUrl(); Assertions.assertTrue(ret.contains("http: System.out.println(ret); }
|
public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: }
|
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } }
|
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } }
|
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } void setDomain(String domain); void setPort(long port); String getServerUrl(); boolean isSkipInit(); void setSkipInit(boolean skipInit); boolean isTesting(); void setTesting(boolean testing); }
|
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } void setDomain(String domain); void setPort(long port); String getServerUrl(); boolean isSkipInit(); void setSkipInit(boolean skipInit); boolean isTesting(); void setTesting(boolean testing); }
|
@Test public void testSendQueue() { for (Object obj : msgArr) { mqService.sendQueue(obj); } }
|
public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } }
|
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } }
|
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } }
|
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }
|
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }
|
@Test public void testSendTopic() { for (Object obj : msgArr) { mqService.sendTopic(obj); } }
|
public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } }
|
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } }
|
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } }
|
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }
|
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }
|
@Test public void testApp() { App.main(null); }
|
public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); }
|
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } }
|
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } }
|
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } static void main(String[] args); }
|
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } static void main(String[] args); }
|
@Test public void testGetInst() { Inst3 inst = Inst3.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; }
|
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } }
|
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); }
|
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); }
|
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); }
|
@Test public void testGetInst() { Inst2 inst = Inst2.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; }
|
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } }
|
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); }
|
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); }
|
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); }
|
@Test public void testGetInst() { Inst4 inst = Inst4.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; }
|
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } }
|
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); }
|
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); }
|
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); }
|
@Test public void testGetMinDifference() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {3, 1, 2, 4}; Assert.assertEquals(0, MinDifference.getMinDifference(arA, n, arB, m)); }
|
public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } static void main(String[] args); static int getMinDifference(int[] arA, int n, int[] arB, int m); }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } static void main(String[] args); static int getMinDifference(int[] arA, int n, int[] arB, int m); }
|
@Test public void testGetInst() { Inst5 inst = Inst5.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
public static Inst5 getInst() { return Holder.inst; }
|
Inst5 { public static Inst5 getInst() { return Holder.inst; } }
|
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); }
|
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); }
|
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); }
|
@Test public void testGetInst() { Inst1 inst = Inst1.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
public static Inst1 getInst() { return inst; }
|
Inst1 { public static Inst1 getInst() { return inst; } }
|
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); }
|
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); }
|
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); }
|
@Test public void testUpload() throws IOException { String filePath = "readme.md"; InputStream fileStream = new FileInputStream(new File(filePath)); boolean ret = FtpUtil.upload("unit-testing", String.format("%d_%s", new Date().getHours(), filePath), fileStream); fileStream.close(); FtpUtil.close(); Assert.assertTrue(ret); }
|
public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; }
|
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; } }
|
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; } }
|
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; } static void close(); static boolean upload(String pathname, String fileName, InputStream inputStream); }
|
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; } static void close(); static boolean upload(String pathname, String fileName, InputStream inputStream); }
|
@Test public void testSendHttpGet() { String html = httpService.sendHttpGet("https: String ret = html.substring(100, 130); System.out.println(ret); Assertions.assertNotNull(ret); }
|
public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); }
|
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } }
|
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } }
|
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }
|
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }
|
@Test public void testBaiduToken() throws UnsupportedEncodingException { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("grant_type", "client_credentials"); put("client_id", "kVcnfD9iW2XVZSMaLMrtLYIz"); put("client_secret", "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6"); }}; JSONObject ret = httpService.sendHttpForm(url, headers, params, new RespJsonObj()); System.out.println(ret); Assertions.assertNotNull(ret); String token = ret.getString("access_token"); testBaiduTts(token); }
|
public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); }
|
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); } }
|
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); } }
|
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }
|
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }
|
@Test public void testTts() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); Object ret = aiController.tts(response, "测试AiController"); System.out.println(ret); Assertions.assertEquals("ok", ret); }
|
@ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; }
|
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; } }
|
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; } }
|
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; } @ApiOperation("语音合成") @GetMapping("/tts") Object tts(HttpServletResponse response, @RequestParam("text") String text); }
|
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; } @ApiOperation("语音合成") @GetMapping("/tts") Object tts(HttpServletResponse response, @RequestParam("text") String text); }
|
@Test public void testUpload() throws IOException { File file = File.createTempFile("tmp", ".txt"); MockMultipartFile multipartFile = new MockMultipartFile( file.getName(), file.getName(), null, new FileInputStream(file) ); Object ret = fileController.upload(multipartFile); System.out.println(ret); String name = (String) ((Map<String, Object>) ret).get("msg"); Assertions.assertNotNull(name); testDownload(name); }
|
@ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; }
|
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; } }
|
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; } }
|
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; } @ApiOperation("上传文件") @PostMapping("/upload") Object upload(@RequestPart MultipartFile file); @ApiOperation("下载文件") @GetMapping("/{name}") void download(HttpServletResponse response, @PathVariable("name") String name); }
|
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; } @ApiOperation("上传文件") @PostMapping("/upload") Object upload(@RequestPart MultipartFile file); @ApiOperation("下载文件") @GetMapping("/{name}") void download(HttpServletResponse response, @PathVariable("name") String name); }
|
@Test public void testGetYYMMDD() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<String, String> io = new HashMap<String, String>() {{ put("yy-MM-dd", "getYYMMDD"); put("yy-MM-dd:HH:mm:ss", "getYYMMDDHHmmSS"); put("HH:mm:ss", "getHHmmSS"); }}; for (Map.Entry<String, String> entry : io.entrySet()) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(entry.getKey()); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.class.getMethod(entry.getValue()).invoke(DateUtil.class)); } }
|
public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); }
|
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } }
|
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } }
|
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }
|
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }
|
@Test public void testGetStringDate() { Date date = mock(Date.class); String[] io = {"yyyy-MM-dd:HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"}; for (String i : io) { String format = i; SimpleDateFormat sdf = new SimpleDateFormat(format); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.getStringDate(format, date)); } }
|
public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); }
|
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } }
|
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } }
|
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }
|
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }
|
@Test public void testApp() { new App().main(null); }
|
public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); }
|
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } }
|
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } }
|
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } static void main(String[] args); }
|
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } static void main(String[] args); }
|
@Test public void testGetMinDifference2() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {1, 4, 2, 3}; Assert.assertEquals(2, MinDifference.getMinDifference(arA, n, arB, m)); }
|
public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } static void main(String[] args); static int getMinDifference(int[] arA, int n, int[] arB, int m); }
|
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } static void main(String[] args); static int getMinDifference(int[] arA, int n, int[] arB, int m); }
|
@Test public void testApp() { App.main(null); }
|
public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); }
|
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); } }
|
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); } }
|
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); } static void main(String[] args); }
|
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); } static void main(String[] args); }
|
@Test public void testPlayUrl() throws Exception { URL fileUrl = new URL("http: Player.asyncPlay(fileUrl); Thread.sleep(3000); }
|
public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); }
|
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } }
|
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } private Player(); }
|
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } private Player(); static void asyncPlay(byte[] audioBytes); static void asyncPlay(URL fileUrl); static void asyncPlay(ByteArrayOutputStream byteOutputStream); @Override void run(); static void play(AudioInputStream audioStream, AudioFormat audioFormat); }
|
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } private Player(); static void asyncPlay(byte[] audioBytes); static void asyncPlay(URL fileUrl); static void asyncPlay(ByteArrayOutputStream byteOutputStream); @Override void run(); static void play(AudioInputStream audioStream, AudioFormat audioFormat); }
|
@Test public void testRecord() throws Exception { RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(null, null); recordHelper.stop(5000); ByteArrayOutputStream ret = recordHelper.save(new ByteArrayOutputStream()); System.out.printf("data: %d\n", ret == null ? 0 : ret.size()); recordHelper.play(); Thread.sleep(3000); File file = recordHelper.save(new File("rec.wav")); System.out.println(file.getName()); }
|
public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); }
|
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } }
|
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); }
|
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); static RecordHelper getInst(); void record(TimeListener timeListener, Long msDuration); void stop(); void stop(long millis); void play(); T save(T fileOrStream); }
|
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); static RecordHelper getInst(); void record(TimeListener timeListener, Long msDuration); void stop(); void stop(long millis); void play(); T save(T fileOrStream); }
|
@Test public void testSplitNumbers() { Map<String, String> ioMap = new HashMap<String, String>() {{ put("101112", "YES 10"); put("1234", "YES 1"); put("91011", "YES 9"); put("99100", "YES 99"); put("101103", "NO"); put("010203", "NO"); put("13", "NO"); put("1", "NO"); put("11111111111111111111111111111111", "NO"); }}; List<BigInteger> numbers = new ArrayList<BigInteger>(); for (Map.Entry<String, String> io : ioMap.entrySet()) { String str = io.getKey(); numbers.clear(); String ret = SplitNumbers.splitStr(str, 0, numbers) ? ("YES " + String.valueOf(numbers.get(0))) : "NO"; if (!ret.equals(io.getValue())) { System.out.printf("%s %s", io.getValue(), ret); } Assert.assertEquals(io.getValue(), ret); } }
|
public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; }
|
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; } }
|
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; } }
|
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; } static boolean splitStr(String str, int index, List<BigInteger> numbers); }
|
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; } static boolean splitStr(String str, int index, List<BigInteger> numbers); }
|
@Test public void testResolve() { Map<Integer, String> ioMap = new HashMap<Integer, String>() {{ put(2016, "12.09.2016"); }}; for (Map.Entry<Integer, String> io : ioMap.entrySet()) { String r = DayOfProgrammer.solve(io.getKey()); if (!io.getValue().equals(r)) { System.out.println(r); } Assert.assertEquals(io.getValue(), r); } }
|
public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); }
|
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); } }
|
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); } }
|
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); } static String solve(int year); }
|
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); } static String solve(int year); static int[] DAYS_OF_MONTH; static int DAY_OF_PROGRAMMER; }
|
@Test public void testFrequency() { String input = "1226#24#"; int[] output = StringDecoder.frequency(input); Assert.assertEquals(1, output[0]); Assert.assertEquals(1, output[1]); }
|
static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; }
|
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; } }
|
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; } }
|
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; } static void main(String[] args); }
|
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; } static void main(String[] args); }
|
@Test public void testSortHotels() { int[] ret = SortHotel.sort_hotels( "breakfast beach citycenter location metro view staff price", new int[]{1, 2, 1, 1, 2}, new String[]{ "This hotel has a nice view of the citycenter. The location is perfect.", "The breakfast is ok. Regarding location, it is quite far from citycenter buth price is cheap so it is worth.", "Location is excellent, 5 minutes from citycenter. There is also a metro station very close to the hotel.", "They said I couldn't take my dog and there were other guests with dogs! That is not fair.", "Very friendly staff and good cost-benefit ratio. Its location is a bit far from citycenter." }); Assert.assertArrayEquals(new int[] {2, 1}, ret); }
|
static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; }
|
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; } }
|
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; } }
|
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; } }
|
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; } }
|
@Test public void testTriangle() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[]{3, 3, 3}, 1); put(new int[]{3, 5, 4}, 2); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int[] i = io.getKey(); int ret = Triangle.triangle(i[0], i[1], i[2]); Assert.assertEquals(io.getValue().intValue(), ret); } }
|
public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; }
|
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } }
|
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } }
|
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }
|
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }
|
@Test public void testTriangleOrNot() { int[] a = {7, 10, 7}; int[] b = {2, 3, 4}; int[] c = {2, 7, 4}; String[] results = Triangle.triangleOrNot(a, b, c); System.out.println(Arrays.asList(results)); }
|
public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; }
|
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; } }
|
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; } }
|
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }
|
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }
|
@Test public void testHowManyAgentsToAdd() { Map<int[][], int[]> mapIO = new HashMap<int[][], int[]>(){{ put(new int[][] {{1481122000, 1481122020}, {1481122000, 1481122040}, {1481122030, 1481122035}}, new int[]{1, 1}); }}; for (Map.Entry<int[][], int[]> io : mapIO.entrySet()) { int ret = CustomerServiceCapacity.howManyAgentsToAdd(io.getValue()[0], io.getKey()); Assert.assertEquals(io.getValue()[1], ret); } }
|
public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; }
|
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; } }
|
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; } }
|
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; } static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes); }
|
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; } static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.