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 givenMerlinsBeardIsConnected_whenGettingNetworkStatus_thenReturnsNetworkStatusAvailable() { given(merlinsBeards.isConnected()).willReturn(CONNECTED); NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus(); assertThat(networkStatus).isEqualTo(NetworkStatus.newAvailableInstance()); }
NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
@Test public void givenMerlinsBeardIsDisconnected_whenGettingNetworkStatus_thenReturnsNetworkStatusUnavailable() { given(merlinsBeards.isConnected()).willReturn(DISCONNECTED); NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus(); assertThat(networkStatus).isEqualTo(NetworkStatus.newUnavailableInstance()); }
NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }
@Test(expected = IllegalStateException.class) public void givenMissingRegister_whenRegisteringBindable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Bindable bindable = mock(Bindable.class); registrar.registerBindable(bindable); }
void registerBindable(Bindable bindable) { bindables().register(bindable); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void givenNetworkIsDisconnected_whenCheckingForConnectivity_thenReturnsFalse() { given(connectivityManager.getActiveNetworkInfo()).willReturn(networkInfo); given(networkInfo.isConnected()).willReturn(DISCONNECTED); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isFalse(); }
public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsNull_whenCheckingForConnectivity_thenReturnsFalse() { given(connectivityManager.getActiveNetworkInfo()).willReturn(null); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isFalse(); }
public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsConnected_whenCheckingForConnectivity_thenReturnsTrue() { given(connectivityManager.getActiveNetworkInfo()).willReturn(networkInfo); given(networkInfo.isConnected()).willReturn(CONNECTED); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isTrue(); }
public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsConnectedViaWifi_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToWifi_thenReturnsTrue() { givenNetworkStateForBelowLollipop(CONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isTrue(); }
public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsDisconnected_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToWifi_thenReturnsFalse() { givenNetworkStateForBelowLollipop(DISCONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); }
public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsConnectedViaWifi_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToWifi_thenReturnsTrue() { givenNetworkStateForLollipopOrAbove(CONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isTrue(); }
public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsDisconnected_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToWifi_thenReturnsFalse() { givenNetworkStateForLollipopOrAbove(DISCONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); }
public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkConnectivityInfoIsUnavailable_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToWifi_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(BELOW_LOLLIPOP); given(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)).willReturn(null); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); }
public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkConnectivityInfoIsUnavailable_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToWifi_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(LOLLIPOP_OR_ABOVE); given(connectivityManager.getAllNetworks()).willReturn(new Network[]{}); boolean connectedToWifi = merlinsBeard.isConnectedToWifi(); assertThat(connectedToWifi).isFalse(); }
public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToWifi() { return isConnectedTo(ConnectivityManager.TYPE_WIFI); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkIsConnectedViaMobile_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToMobile_thenReturnsTrue() { givenNetworkStateForBelowLollipop(CONNECTED, ConnectivityManager.TYPE_MOBILE); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isTrue(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenRegister_whenRegisteringConnectable_thenRegistersConnectableWithConnector() { Connectable connectable = mock(Connectable.class); registrar.registerConnectable(connectable); verify(connectables).register(connectable); }
void registerConnectable(Connectable connectable) { connectables().register(connectable); }
Registrar { void registerConnectable(Connectable connectable) { connectables().register(connectable); } }
Registrar { void registerConnectable(Connectable connectable) { connectables().register(connectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerConnectable(Connectable connectable) { connectables().register(connectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerConnectable(Connectable connectable) { connectables().register(connectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void givenNetworkIsDisconnected_andAndroidVersionIsBelowLollipop_whenCheckingIfConnectedToMobile_thenReturnsFalse() { givenNetworkStateForBelowLollipop(DISCONNECTED, ConnectivityManager.TYPE_WIFI); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isFalse(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenSuccessfulPing_whenCheckingCaptivePortal_thenCallsOnResultWithTrue() { willAnswer(new Answer<EndpointPinger.PingerCallback>() { @Override public EndpointPinger.PingerCallback answer(InvocationOnMock invocation) { EndpointPinger.PingerCallback cb = invocation.getArgument(0); cb.onSuccess(); return cb; } }).given(endpointPinger).ping(any(EndpointPinger.PingerCallback.class)); merlinsBeard.hasInternetAccess(mockCaptivePortalCallback); then(mockCaptivePortalCallback).should().onResult(true); }
public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenFailurePing_whenCheckingCaptivePortal_thenCallsOnResultWithFalse() { willAnswer(new Answer<EndpointPinger.PingerCallback>() { @Override public EndpointPinger.PingerCallback answer(InvocationOnMock invocation) { EndpointPinger.PingerCallback cb = invocation.getArgument(0); cb.onFailure(); return cb; } }).given(endpointPinger).ping(any(EndpointPinger.PingerCallback.class)); merlinsBeard.hasInternetAccess(mockCaptivePortalCallback); then(mockCaptivePortalCallback).should().onResult(false); }
public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenSuccessfulPing_whenCheckingHasInternetAccessSync_thenReturnsTrue() { given(mockPing.doSynchronousPing()).willReturn(true); boolean result = merlinsBeard.hasInternetAccess(); assertThat(result).isTrue(); }
public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenFailedPing_whenCheckingHasInternetAccessSync_thenReturnsFalse() { given(mockPing.doSynchronousPing()).willReturn(false); boolean result = merlinsBeard.hasInternetAccess(); assertThat(result).isFalse(); }
public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public void hasInternetAccess(final InternetAccessCallback callback) { captivePortalPinger.ping(new EndpointPinger.PingerCallback() { @Override public void onSuccess() { callback.onResult(true); } @Override public void onFailure() { callback.onResult(false); } }); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsConnectedViaMobile_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsTrue() { givenNetworkStateForLollipopOrAbove(CONNECTED, ConnectivityManager.TYPE_MOBILE); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isTrue(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkIsDisconnected_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { givenNetworkStateForLollipopOrAbove(DISCONNECTED, ConnectivityManager.TYPE_MOBILE); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isFalse(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenNetworkConnectivityInfoIsUnavailable_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(false); given(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)).willReturn(null); boolean connectedToWifi = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToWifi).isFalse(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNoAvailableNetworks_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { given(androidVersion.isLollipopOrHigher()).willReturn(true); given(connectivityManager.getAllNetworks()).willReturn(new Network[]{}); boolean connectedToWifi = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToWifi).isFalse(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenNetworkWithoutNetworkInfo_andAndroidVersionIsLollipopOrAbove_whenCheckingIfConnectedToMobile_thenReturnsFalse() { givenNetworkStateWithoutNetworkInfoForLollipopOrAbove(); boolean connectedToMobileNetwork = merlinsBeard.isConnectedToMobileNetwork(); assertThat(connectedToMobileNetwork).isFalse(); }
public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
MerlinsBeard { public boolean isConnectedToMobileNetwork() { return isConnectedTo(ConnectivityManager.TYPE_MOBILE); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }
@Test public void givenRegister_whenRegisteringDisconnectable_thenRegistersDisconnectableWithDisconnector() { Disconnectable disconnectable = mock(Disconnectable.class); registrar.registerDisconnectable(disconnectable); verify(this.disconnectables).register(disconnectable); }
void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); }
Registrar { void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); } }
Registrar { void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void givenRegisteredDisconnectable_whenCallingOnDisconect_thenCallsDisconnectForDisconnectable() { Disconnectable disconnectable = givenRegisteredDisconnectable(); disconnectCallbackManager.onDisconnect(); verify(disconnectable).onDisconnect(); }
@Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); @Override void onDisconnect(); }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); @Override void onDisconnect(); }
@Test public void givenMultipleRegisteredDisconnectables_whenCallingOnConnect_thenCallsConnectForAllDisconnectables() { List<Disconnectable> disconnectables = givenMultipleRegisteredDisconnectables(); disconnectCallbackManager.onDisconnect(); for (Disconnectable disconnectable : disconnectables) { verify(disconnectable).onDisconnect(); } }
@Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); @Override void onDisconnect(); }
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); @Override void onDisconnect(); }
@Test public void givenIntentWithNoConnectivityOfConnected_whenCreatingAConnectivityChangeEvent_thenReturnsConnectedConnectivityChangeEvent() { givenIntentWithNoConnectivityExtraOf(CONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); }
ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
@Test public void givenIntentWithNoConnectivityOfDisconnected_whenCreatingAConnectivityChangeEvent_thenReturnsDisconnectedConnectivityChangeEvent() { givenIntentWithNoConnectivityExtraOf(DISCONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( DISCONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); }
ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
@Test public void givenMerlinsBeardIsConnected_whenCreatingAConnectivityChangeEvent_thenReturnsConnectedConnectivityChangeEvent() { givenMerlinsBeardIs(CONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); }
ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
@Test public void givenMerlinsBeardIsDisconnected_whenCreatingAConnectivityChangeEvent_thenReturnsDisconnectedConnectivityChangeEvent() { givenMerlinsBeardIs(DISCONNECTED); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); ConnectivityChangeEvent expectedConnectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( DISCONNECTED, ANY_INFO, ANY_REASON ); assertThat(connectivityChangeEvent).isEqualTo(expectedConnectivityChangeEvent); }
ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
ConnectivityChangeEventCreator { ConnectivityChangeEvent createFrom(Intent intent, MerlinsBeard merlinsBeard) { boolean isConnected = extractIsConnectedFrom(intent, merlinsBeard); String info = intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(isConnected, info, reason); } }
@Test public void givenRegisteredConnectable_whenCallingOnConnect_thenCallsConnectForConnectable() { Connectable connectable = givenRegisteredConnectable(); connectCallbackManager.onConnect(); verify(connectable).onConnect(); }
void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
@Test public void givenMultipleRegisteredConnectables_whenCallingOnConnect_thenCallsConnectForAllConnectables() { List<Connectable> connectables = givenMultipleRegisteredConnectables(); connectCallbackManager.onConnect(); for (Connectable connectable : connectables) { verify(connectable).onConnect(); } }
void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
@Test public void givenRegisteredConnectable_whenCallingOnConnectAndAddingConnectable_thenCallsConnectForConnectable() { Connectable connectable = givenRegisteredConnectableModifyingConnectables(); connectCallbackManager.onConnect(); verify(connectable).onConnect(); }
void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }
@Test public void givenOnBindHasBeenCalled_whenCheckingIsBound_thenReturnsTrue() { givenBoundMerlinService(); boolean bound = MerlinService.isBound(); assertThat(bound).isTrue(); }
public static boolean isBound() { return isBound; }
MerlinService extends Service { public static boolean isBound() { return isBound; } }
MerlinService extends Service { public static boolean isBound() { return isBound; } }
MerlinService extends Service { public static boolean isBound() { return isBound; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
MerlinService extends Service { public static boolean isBound() { return isBound; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenRegister_whenRegisteringBindable_thenRegistersBindableWithBinder() { Bindable bindable = mock(Bindable.class); registrar.registerBindable(bindable); verify(bindables).register(bindable); }
void registerBindable(Bindable bindable) { bindables().register(bindable); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void givenBoundMerlinService_whenCallingOnUnbind_thenUnregistersConnectivityChangesRegister() { givenBoundMerlinService(); merlinService.onUnbind(intent); verify(connectivityChangesRegister).unregister(); }
@Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenConnectivityChangesRegisterIsNotBound_whenBindCompletes_thenThrowsException_andStopsWorkOnService() { thrown.expect(MerlinServiceDependencyMissingExceptionMatcher.from(ConnectivityChangesRegister.class)); MerlinService.LocalBinder binder = (MerlinService.LocalBinder) merlinService.onBind(intent); binder.setConnectivityChangesForwarder(connectivityChangesForwarder); binder.onBindComplete(); verifyZeroInteractions(connectivityChangesRegister); verifyZeroInteractions(connectivityChangesForwarder); }
@Override public IBinder onBind(Intent intent) { isBound = true; return binder; }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenConnectivityChangesForwarderIsNotBound_whenBindCompletes_thenThrowsException_andStopsWorkOnService() { thrown.expect(MerlinServiceDependencyMissingExceptionMatcher.from(ConnectivityChangesForwarder.class)); MerlinService.LocalBinder binder = (MerlinService.LocalBinder) merlinService.onBind(intent); binder.setConnectivityChangesRegister(connectivityChangesRegister); binder.onBindComplete(); verifyZeroInteractions(connectivityChangesRegister); verifyZeroInteractions(connectivityChangesForwarder); }
@Override public IBinder onBind(Intent intent) { isBound = true; return binder; }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenUnboundService_whenNotifying_thenDoesNotForwardEvent() { MerlinService.LocalBinder localBinder = givenBoundMerlinService(); merlinService.onUnbind(null); localBinder.notify(ANY_CONNECTIVITY_CHANGE_EVENT); verifyZeroInteractions(connectivityChangesForwarder); }
@Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }
@Test public void givenConnectedNetworkInfo_whenNetworkIsAvailable_thenNotifiesOfConnectedNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(CONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onAvailable(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); }
@Override public void onAvailable(Network network) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenDisconnectedNetworkInfo_whenLosingNetwork_thenNotifiesOfDisconnectedNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(DISCONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onLosing(network, MAX_MS_TO_LIVE); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); }
@Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenDisconnectedNetworkInfo_whenNetworkIsLost_thenNotifiesOfLostNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(DISCONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onLost(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); }
@Override public void onLost(Network network) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenNoNetworkInfo_whenNetworkIsAvailable_thenNotifiesOfConnectedNetwork() { networkCallbacks.onAvailable(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); }
@Override public void onAvailable(Network network) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenNoNetworkInfo_whenLosingNetwork_thenNotifiesOfDisconnectedNetwork() { networkCallbacks.onLosing(network, MAX_MS_TO_LIVE); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); }
@Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenNoNetworkInfo_whenNetworkIsLost_thenNotifiesOfLostNetwork() { networkCallbacks.onLost(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); }
@Override public void onLost(Network network) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void whenClearingRegistrations_thenDelegatesClearingToRegisters() { registrar.clearRegistrations(); verify(connectables).clear(); verify(disconnectables).clear(); verify(bindables).clear(); }
void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void givenCannotNotify_whenNetworkIsAvailable_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onAvailable(MISSING_NETWORK); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); }
@Override public void onAvailable(Network network) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenCannotNotify_whenLosingNetwork_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onLosing(MISSING_NETWORK, MAX_MS_TO_LIVE); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); }
@Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void givenCannotNotify_whenNetworkIsLost_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onLost(MISSING_NETWORK); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); }
@Override public void onLost(Network network) { notifyMerlinService(network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier, ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }
@Test public void unbindWhenUnsubscribed() { Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); verify(merlin).unbind(); }
public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Observable<NetworkStatus> from(Context context); static Observable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Observable<NetworkStatus> from(Merlin merlin); }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Observable<NetworkStatus> from(Context context); static Observable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Observable<NetworkStatus> from(Merlin merlin); }
@Test public void notCrashWhenCreatingWithAMerlinBuilderWithoutCallbacks() { Context context = mock(Context.class); Merlin.Builder merlinBuilder = new Merlin.Builder(); MerlinObservable.from(context, merlinBuilder).subscribe(); }
public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Observable<NetworkStatus> from(Context context); static Observable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Observable<NetworkStatus> from(Merlin merlin); }
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Observable<NetworkStatus> from(Context context); static Observable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Observable<NetworkStatus> from(Merlin merlin); }
@Test public void givenMissingConnectables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(null, disconnectables, bindables); registrar.clearRegistrations(); verifyZeroInteractions(connectables); }
void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }
@Test public void testOnCreateShouldExtractStateFromIntent() throws JSONException { OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class, createStartIntent() ).create().get(); assertThat(activity.mCompleteIntent).isEqualTo(this.mCompleteIntent); assertThat(activity.mCancelIntent).isEqualTo(this.mCancelIntent); }
static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
@Test public void testReadStateLocksPreferencesBeforeActing() { assertThat(mPrefs.contains(KEY_STATE)).isFalse(); mPrefsLock.lock(); try { sut.readState(); fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown"); } catch (IllegalStateException e) { assertThat(mPrefsLock.getHoldCount()).isEqualTo(1); } mPrefsLock.unlock(); assertThat(sut.readState()).isNotNull(); assertThat(mPrefsLock.getHoldCount()).isEqualTo(0); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); }
@AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } }
AuthStateManager { @AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } } }
AuthStateManager { @AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); }
AuthStateManager { @AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
AuthStateManager { @AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testWriteStateLocksPreferencesBeforeActing() { assertThat(mPrefs.contains(KEY_STATE)).isFalse(); mPrefsLock.lock(); try { sut.writeState(new AuthState()); fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown"); } catch (IllegalStateException e) { assertThat(mPrefsLock.getHoldCount()).isEqualTo(1); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); } mPrefsLock.unlock(); sut.writeState(new AuthState()); assertThat(mPrefsLock.getHoldCount()).isEqualTo(0); assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull(); }
@AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testWriteStateRemovesKeyWhenWritingNull() { sut.writeState(new AuthState()); assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull(); sut.writeState(null); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); }
@AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testRefreshWithoutTokenCallsListener() { FakeOktaAuthListener listener = new FakeOktaAuthListener(); sut.refreshAccessToken(listener); assertThat(listener.hasCalledOnTokenFailure()).isTrue(); assertThat(listener.getTokenExceptions().get(0)) .isEqualTo(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); }
public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testRefreshFailsClientAuthenticationCallsListener() throws ClientAuthentication.UnsupportedAuthenticationMethod { when(mAuthState.getRefreshToken()).thenReturn("refreshTokenHere"); when(mAuthState.getClientAuthentication()) .thenThrow(new ClientAuthentication. UnsupportedAuthenticationMethod("tokenEndpointAuthMethod")); FakeOktaAuthListener listener = new FakeOktaAuthListener(); sut.refreshAccessToken(listener); verify(mAuthState, times(1)).getClientAuthentication(); assertThat(listener.hasCalledOnTokenFailure()).isTrue(); assertThat(listener.getTokenExceptions().get(0)) .isEqualTo(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); }
public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testSignOutFromOkta() { PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); String idToken = TestUtils.getUnsignedIdToken(); when(mAuthService.createCustomTabsIntentBuilder(any(Uri.class))) .thenReturn(new CustomTabsIntent.Builder()); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); when(authState.isAuthorized()).thenReturn(true); when(authState.getIdToken()).thenReturn(idToken); when(mConfiguration.getEndSessionRedirectUri()) .thenReturn(TestUtils.TEST_APP_REDIRECT_URI); when(mConfiguration.hasConfigurationChanged()).thenReturn(false); ArgumentCaptor<EndSessionRequest> argument = ArgumentCaptor.forClass(EndSessionRequest.class); sut.signOutFromOkta(mContext, success, failure); verify(mAuthService, times(1)) .performEndOfSessionRequest( argument.capture() ,any(PendingIntent.class) ,any(PendingIntent.class) ,any(CustomTabsIntent.class) ); assertThat(argument.getValue().idToken) .isEqualTo(idToken); assertThat(argument.getValue().configuration.toJsonString()) .isEqualTo(TestUtils.getTestServiceConfig().toJsonString()); assertThat(argument.getValue().redirectUri) .isEqualTo(TestUtils.TEST_APP_REDIRECT_URI); }
public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test(expected = IllegalStateException.class) public void testLogoutNoLogedinUserFoundException(){ PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.isAuthorized()).thenReturn(false); when(mConfiguration.hasConfigurationChanged()).thenReturn(false); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); sut.signOutFromOkta(mContext, success, failure); }
public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ) { if (!isUserLoggedIn()) { throw new IllegalStateException("No logged in user found"); } mExecutor.submit(new Runnable() { @Override public void run() { doEndSession( OktaManagementActivity.createStartIntent( context, completionIntent, cancelIntent), cancelIntent); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testLoginWithoutPayloadSuccess() { PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); AuthorizationRequest expectedRequest = TestUtils.getTestAuthRequest(); when(mAuthService.createCustomTabsIntentBuilder(any(Uri.class))) .thenReturn(new CustomTabsIntent.Builder()); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); sut.mAuthRequest.set(TestUtils.getTestAuthRequest()); sut.login(mContext, success, failure); ArgumentCaptor<AuthorizationRequest> argument = ArgumentCaptor.forClass(AuthorizationRequest.class); verify(mAuthService, times(1)) .performAuthorizationRequest( argument.capture() ,any(PendingIntent.class) ,any(PendingIntent.class) ,any(CustomTabsIntent.class) ); assertThat(expectedRequest.clientId) .isEqualTo(argument.getValue().clientId); assertThat(expectedRequest.configuration.toJsonString()) .isEqualTo(argument.getValue().configuration.toJsonString()); }
public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testLoginWithPayloadSuccess() { PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState authState = mock(AuthState.class); when(mAuthService.createCustomTabsIntentBuilder(any(Uri.class))) .thenReturn(new CustomTabsIntent.Builder()); when(mAuthStateManager.getCurrent()).thenReturn(authState); when(authState.getAuthorizationServiceConfiguration()) .thenReturn(TestUtils.getTestServiceConfig()); when(mConfiguration.getRedirectUri()).thenReturn(TestUtils.TEST_APP_REDIRECT_URI); when(mConfiguration.getScopes()).thenReturn(new HashSet<>(TestUtils.TEST_SCOPES_SUPPORTED)); sut.mClientId.set(TestUtils.TEST_CLIENT_ID); AuthenticationPayload payload = new AuthenticationPayload.Builder() .addParameter("testName", "testValue") .setState("testState") .setLoginHint("loginHint") .build(); sut.login(mContext, success, failure, payload); ArgumentCaptor<AuthorizationRequest> argument = ArgumentCaptor .forClass(AuthorizationRequest.class); verify(mAuthService, times(1)) .performAuthorizationRequest( argument.capture() ,any(PendingIntent.class) ,any(PendingIntent.class) ,any(CustomTabsIntent.class) ); assertThat(argument.getValue().loginHint) .isEqualTo(payload.getLoginHint()); assertThat(argument.getValue().additionalParameters) .isEqualTo(payload.getAdditionalParameters()); assertThat(argument.getValue().state) .isEqualTo(payload.getState()); }
public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testLoginIllegalStateExceptionConfigurationChanged(){ PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); when(mConfiguration.hasConfigurationChanged()).thenReturn(true); try { sut.login(mContext, success, failure); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta Configuration has changed"); return; } fail("Expected exception not thrown"); }
public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testOnStartShouldSignOutIfConfigurationHasChanged() throws CanceledException, JSONException { Context context = RuntimeEnvironment.application.getApplicationContext(); new OAuthClientConfiguration( context, context.getSharedPreferences(OAuthClientConfiguration.PREFS_NAME, MODE_PRIVATE), ConfigurationStreams.getOtherConfiguration() ); doNothing().when(mCancelIntent).send(); OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class ).newIntent(createStartIntent()).create().start().get(); assertThat(activity.isFinishing()).isTrue(); }
static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
@Test public void testLoginIllegalStateExceptionNoAuthorizationConfiguration(){ PendingIntent success = mock(PendingIntent.class); PendingIntent failure = mock(PendingIntent.class); AuthState mockedState = mock(AuthState.class); when(mAuthStateManager.getCurrent()).thenReturn(mockedState); when(mockedState.getAuthorizationServiceConfiguration()).thenReturn(null); try { sut.login(mContext, success, failure); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta should be initialized first"); return; } fail("Expected exception not thrown"); }
public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent) { login(context, completionIntent, cancelIntent, null); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testRefreshCallsIntoAppAuth() throws ClientAuthentication.UnsupportedAuthenticationMethod { TokenRequest tokenRequest = mock(TokenRequest.class); FakeOktaAuthListener listener = new FakeOktaAuthListener(); when(mAuthState.getRefreshToken()).thenReturn("refreshTokenHere"); when(mAuthState.getClientAuthentication()).thenReturn(mClientAuthentication); when(mAuthState.createTokenRefreshRequest()).thenReturn(tokenRequest); sut.refreshAccessToken(listener); verify(mAuthService, times(1)) .performTokenRequest( any(TokenRequest.class), any(ClientAuthentication.class), any(AuthorizationService.TokenResponseCallback.class)); }
public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void refreshAccessToken(final OktaAuthListener listener) { if (!hasRefreshToken()) { Log.d(TAG, "Calling refreshAccessToken without a refresh token"); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } ClientAuthentication clientAuthentication; try { clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication(); } catch (UnsupportedAuthenticationMethod ex) { Log.e(TAG, "Token request cannot be made; client authentication for the token " + "endpoint could not be constructed (%s)", ex); listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST); return; } createAuthorizationServiceIfNeeded().performTokenRequest( mAuthStateManager.getCurrent().createTokenRefreshRequest(), clientAuthentication, new AuthorizationService.TokenResponseCallback() { @Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authException) { handleAccessTokenResponse( tokenResponse, authException, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testGetTokenSuccess() { String testIdToken = "testIdToken"; String testAccessToken = "testAccessToken"; String testRefreshToken = "testRefreshToken"; when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getIdToken()).thenReturn(testIdToken); when(mAuthState.getRefreshToken()).thenReturn(testRefreshToken); when(mAuthState.getAccessToken()).thenReturn(testAccessToken); Tokens tokens = sut.getTokens(); assertThat(tokens.getAccessToken()).isEqualTo(testAccessToken); assertThat(tokens.getIdToken()).isEqualTo(testIdToken); assertThat(tokens.getRefreshToken()).isEqualTo(testRefreshToken); }
public Tokens getTokens() { return Tokens.fromAuthState(mAuthStateManager.getCurrent()); }
OktaAppAuth { public Tokens getTokens() { return Tokens.fromAuthState(mAuthStateManager.getCurrent()); } }
OktaAppAuth { public Tokens getTokens() { return Tokens.fromAuthState(mAuthStateManager.getCurrent()); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public Tokens getTokens() { return Tokens.fromAuthState(mAuthStateManager.getCurrent()); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public Tokens getTokens() { return Tokens.fromAuthState(mAuthStateManager.getCurrent()); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testAccessTokenRevocationSuccess() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testAccessToken) && url.contains(testClientId)){ return new MockResponse().setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(testAccessToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(true); latch.countDown(); } @Override public void onError(AuthorizationException ex) { isPassed.set(false); latch.countDown(); } }); latch.await(); assertTrue("onError has been called",isPassed.get()); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testAccessTokenRevocationFailure() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testAccessToken) && url.contains(testClientId)){ return new MockResponse().setResponseCode(400); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(testAccessToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(false); latch.countDown(); } @Override public void onError(AuthorizationException ex) { if (ex.type == AuthorizationException.TYPE_OAUTH_TOKEN_ERROR) { isPassed.set(true); } latch.countDown(); } }); latch.await(); assertTrue("onSuccess has been called",isPassed.get()); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testAllTokenRevocationSuccess() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testRefreshToke = "testRefreshToke"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testClientId) && (url.contains(testAccessToken) || url.contains(testRefreshToke)) ){ return new MockResponse().setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); when(mAuthState.getAccessToken()).thenReturn(testAccessToken); when(mAuthState.getRefreshToken()).thenReturn(testRefreshToke); when(mAuthState.isAuthorized()).thenReturn(true); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(true); latch.countDown(); } @Override public void onError(AuthorizationException ex) { isPassed.set(false); latch.countDown(); } }); latch.await(); assertTrue("onError has been called",isPassed.get()); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testAllTokenRevocationNoRefreshTokenSuccess() throws JSONException, InterruptedException { final String testAccessToken = "testAccesToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testClientId) && (url.contains(testAccessToken)) ){ return new MockResponse().setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); when(mAuthState.getAccessToken()).thenReturn(testAccessToken); when(mAuthState.getRefreshToken()).thenReturn(null); when(mAuthState.isAuthorized()).thenReturn(true); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(true); latch.countDown(); } @Override public void onError(AuthorizationException ex) { isPassed.set(false); latch.countDown(); } }); latch.await(); assertTrue("onError has been called",isPassed.get()); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testAllTokenRevocationRefreshTokenFailure() throws JSONException, InterruptedException { final String testRefreshToken = "testRefreshToken"; final String testClientId = "clientId"; AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class); AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class); MockWebServer mockWebServer = new MockWebServer(); mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { String url = request.getPath(); if (url.contains(TestUtils.REVOKE_URI) && url.contains(testClientId) && (url.contains(testRefreshToken)) ){ return new MockResponse().setResponseCode(400); } return new MockResponse().setResponseCode(404); } }); String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString(); sut.mClientId.set(testClientId); ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils .addField(new JSONObject(), RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl )); ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc); when(mAuthStateManager.getCurrent()).thenReturn(mAuthState); when(mAuthState.getAuthorizationServiceConfiguration()) .thenReturn(configurationMoc); when(mAuthState.getRefreshToken()).thenReturn(testRefreshToken); when(mAuthState.isAuthorized()).thenReturn(true); final AtomicBoolean isPassed = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); sut.revoke(new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { isPassed.set(false); latch.countDown(); } @Override public void onError(AuthorizationException ex) { if (ex.type == AuthorizationException.TYPE_OAUTH_TOKEN_ERROR) { isPassed.set(true); } latch.countDown(); } }); latch.await(); assertTrue("onSuccess has been called",isPassed.get()); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testTokenRevocationConfigChangedException() { String testToken = "testToken"; when(mConfiguration.hasConfigurationChanged()).thenReturn(true); try { sut.revoke(testToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { fail("Test should fail with exception"); } @Override public void onError(AuthorizationException ex) { fail("Test should fail with exception"); } }); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta Configuration has changed"); return; } fail("Test should fail with exception"); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testTokenRevocationOktaNotInitializedException() { String testToken = "testToken"; AuthState mockedState = mock(AuthState.class); when(mAuthStateManager.getCurrent()).thenReturn(mockedState); when(mockedState.getAuthorizationServiceConfiguration()).thenReturn(null); try { sut.revoke(testToken, new OktaAppAuth.OktaRevokeListener() { @Override public void onSuccess() { fail("Test should fail with exception"); } @Override public void onError(AuthorizationException ex) { fail("Test should fail with exception"); } }); } catch (IllegalStateException ex) { assertThat(ex).isInstanceOf(IllegalStateException.class); assertThat(ex.getMessage()).contains("Okta should be initialized first"); return; } fail("Test should fail with exception"); }
public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
OktaAppAuth { public void revoke(final String token, @NonNull final OktaRevokeListener listener) { if (mConfiguration.hasConfigurationChanged()) { throw new IllegalStateException("Okta Configuration has changed"); } if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) { throw new IllegalStateException("Okta should be initialized first"); } mExecutor.submit(new Runnable() { @Override public void run() { doRevoke(token, listener); } }); } @AnyThread protected OktaAppAuth(Context context); @AnyThread static OktaAppAuth getInstance(@NonNull Context context); @AnyThread void init( final Context context, final OktaAuthListener listener); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor); @AnyThread void init( final Context context, final OktaAuthListener listener, @ColorInt int customTabColor, final OktaConnectionBuilder oktaConnectionBuilder); void revoke(final String token, @NonNull final OktaRevokeListener listener); void revoke(@NonNull final OktaRevokeListener listener); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent); void login( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent, final AuthenticationPayload payload); void authenticate( final String sessionToken, @Nullable final OktaNativeAuthListener listener); void signOutFromOkta( final Context context, final PendingIntent completionIntent, final PendingIntent cancelIntent ); void clearSession(); void dispose(); @AnyThread boolean isUserLoggedIn(); boolean hasRefreshToken(); boolean hasAccessToken(); Long getAccessTokenExpirationTime(); void refreshAccessToken(final OktaAuthListener listener); boolean hasIdToken(); void getUserInfo(final OktaAuthActionCallback<JSONObject> callback); void performAuthorizedRequest(final BearerAuthRequest action); Tokens getTokens(); }
@Test public void testOnStartShouldCompleteIfStateIsAuthorized() throws CanceledException, JSONException { Context context = RuntimeEnvironment.application.getApplicationContext(); AuthStateManager stateManager = AuthStateManager.getInstance(context); stateManager.replace(mAuthState); when(mAuthState.isAuthorized()).thenReturn(true); doNothing().when(mCompleteIntent).send(); OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class, createStartIntent() ).create().start().get(); assertThat(activity.isFinishing()).isTrue(); }
static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }
@Test public void testInValidCredentialsPerformAuthorizationRequest() { FakeNativeOktaAuthListener listener = new FakeNativeOktaAuthListener(); sessionAuthenticationService.performAuthorizationRequest(request, null, listener); assertTrue(listener.hasCalledOnTokenFailure()); }
void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
@Test public void testNullListenerPerformAuthorizationRequest() { sessionAuthenticationService.performAuthorizationRequest(request, VALID_SESSION, null); sessionAuthenticationService.performAuthorizationRequest(request, null, null); }
void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService( AuthStateManager manager, AuthorizationService authorizationService, ConnectionBuilder connectionBuilder); }
@Test public void testGetClientId() { assertThat(sut.getClientId()).isEqualTo("example_client_id"); }
public String getClientId() { return mClientId; }
OAuthClientConfiguration { public String getClientId() { return mClientId; } }
OAuthClientConfiguration { public String getClientId() { return mClientId; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); }
OAuthClientConfiguration { public String getClientId() { return mClientId; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
OAuthClientConfiguration { public String getClientId() { return mClientId; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void getRedirectUri() { assertThat(sut.getRedirectUri()).isEqualTo( Uri.parse("com.okta.appauth.android.test:/oauth2redirect")); }
public Uri getRedirectUri() { return mRedirectUri; }
OAuthClientConfiguration { public Uri getRedirectUri() { return mRedirectUri; } }
OAuthClientConfiguration { public Uri getRedirectUri() { return mRedirectUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); }
OAuthClientConfiguration { public Uri getRedirectUri() { return mRedirectUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
OAuthClientConfiguration { public Uri getRedirectUri() { return mRedirectUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void testGetDiscoveryUriAppendsWellKnownDiscovery() { assertThat(sut.getDiscoveryUri()).isEqualTo( Uri.parse("https: ); }
public Uri getDiscoveryUri() { return mDiscoveryUri; }
OAuthClientConfiguration { public Uri getDiscoveryUri() { return mDiscoveryUri; } }
OAuthClientConfiguration { public Uri getDiscoveryUri() { return mDiscoveryUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); }
OAuthClientConfiguration { public Uri getDiscoveryUri() { return mDiscoveryUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
OAuthClientConfiguration { public Uri getDiscoveryUri() { return mDiscoveryUri; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void testGetScopes() { assertThat(sut.getScopes()).contains("openid", "foo"); }
public Set<String> getScopes() { return mScopes; }
OAuthClientConfiguration { public Set<String> getScopes() { return mScopes; } }
OAuthClientConfiguration { public Set<String> getScopes() { return mScopes; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); }
OAuthClientConfiguration { public Set<String> getScopes() { return mScopes; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
OAuthClientConfiguration { public Set<String> getScopes() { return mScopes; } @VisibleForTesting OAuthClientConfiguration( final Context context, final SharedPreferences prefs, final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }
@Test public void testGetCurrentCachesState() { AuthState state = sut.getCurrent(); assertThat(sut.getCurrent()).isSameAs(state); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); }
@AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } }
AuthStateManager { @AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } } }
AuthStateManager { @AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); }
AuthStateManager { @AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
AuthStateManager { @AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization( @Nullable AuthorizationResponse response, @Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse( @Nullable TokenResponse response, @Nullable AuthorizationException ex); }
@Test public void testScrollBarDisabled() { pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); assertThat(pane.lookupAll("*")) .haveExactly(1, createBarCondition(HORIZONTAL, false)) .haveExactly(1, createBarCondition(VERTICAL, false)); }
public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); }
GesturePane extends Control implements GesturePaneOps { public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); } }
GesturePane extends Control implements GesturePaneOps { public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testSetTarget() { pane.setTarget(new Transformable() { @Override public double width() { return 128; } @Override public double height() { return 128; } @Override public void setTransform(Affine affine) { } }); pane.setTarget(new Transformable() { @Override public double width() { return 1014; } @Override public double height() { return 1024; } @Override public void setTransform(Affine affine) { } }); }
public void setTarget(Transformable target) { this.target.set(target); }
GesturePane extends Control implements GesturePaneOps { public void setTarget(Transformable target) { this.target.set(target); } }
GesturePane extends Control implements GesturePaneOps { public void setTarget(Transformable target) { this.target.set(target); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public void setTarget(Transformable target) { this.target.set(target); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public void setTarget(Transformable target) { this.target.set(target); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testSetContent() { pane.setContent(new Rectangle(128, 128)); pane.setContent(new Rectangle(1024, 1024)); }
public void setContent(Node content) { this.content.set(content); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testContentBoundChanged() throws Exception { Rectangle rect = new Rectangle(128, 128, Color.RED); pane.setContent(rect); Thread.sleep(50); rect.setWidth(1000); rect.setHeight(1000); Thread.sleep(50); rect.setHeight(0); rect.setHeight(0); }
public void setContent(Node content) { this.content.set(content); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public void setContent(Node content) { this.content.set(content); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testViewportCentre() { pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); assertThat(pane.viewportCentre()).isEqualTo(new Point2D(256, 256)); }
public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); }
GesturePane extends Control implements GesturePaneOps { public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); } }
GesturePane extends Control implements GesturePaneOps { public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testTargetPointAtViewportCentre() { pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); Point2D expected = pane.targetPointAt(pane.viewportCentre()) .orElseThrow(AssertionError::new); assertThat(pane.targetPointAtViewportCentre()).isEqualTo(expected); }
public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { throw new RuntimeException(e); } }
GesturePane extends Control implements GesturePaneOps { public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { throw new RuntimeException(e); } } }
GesturePane extends Control implements GesturePaneOps { public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { throw new RuntimeException(e); } } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { throw new RuntimeException(e); } } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { throw new RuntimeException(e); } } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testScale() { pane.zoomTo(2, pane.targetPointAtViewportCentre()); assertThat(pane.getCurrentScale()).isEqualTo(2d); }
final void scale(double factor, Point2D origin) { scale(factor, factor, origin); }
GesturePane extends Control implements GesturePaneOps { final void scale(double factor, Point2D origin) { scale(factor, factor, origin); } }
GesturePane extends Control implements GesturePaneOps { final void scale(double factor, Point2D origin) { scale(factor, factor, origin); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { final void scale(double factor, Point2D origin) { scale(factor, factor, origin); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { final void scale(double factor, Point2D origin) { scale(factor, factor, origin); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testScaleByTouch() { double factor = 4.2; pane.fireEvent(new ZoomEvent(ZoomEvent.ZOOM, 0, 0, 0, 0, false, false, false, false, false, false, factor, factor, null)); assertThat(pane.getCurrentScale()).isEqualTo(factor); }
public double getCurrentScale() { return scaleX.get(); }
GesturePane extends Control implements GesturePaneOps { public double getCurrentScale() { return scaleX.get(); } }
GesturePane extends Control implements GesturePaneOps { public double getCurrentScale() { return scaleX.get(); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { public double getCurrentScale() { return scaleX.get(); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { public double getCurrentScale() { return scaleX.get(); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testCentreOn() { final double zoom = 2d; final double dx = 300d; final double dy = 200d; pane.setScrollBarPolicy(ScrollBarPolicy.NEVER); pane.zoomTo(zoom, pane.targetPointAtViewportCentre()); final Transform last = target.captureTransform(); pane.centreOn(new Point2D(dx, dy)); final Transform now = target.captureTransform(); assertThat(now.getTx()).isEqualTo(-last.getTx() - dx * zoom); assertThat(now.getTy()).isEqualTo(-last.getTy() - dy * zoom); }
@Override public void centreOn(Point2D pointOnTarget) { Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); }
GesturePane extends Control implements GesturePaneOps { @Override public void centreOn(Point2D pointOnTarget) { Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } }
GesturePane extends Control implements GesturePaneOps { @Override public void centreOn(Point2D pointOnTarget) { Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); }
GesturePane extends Control implements GesturePaneOps { @Override public void centreOn(Point2D pointOnTarget) { Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); }
GesturePane extends Control implements GesturePaneOps { @Override public void centreOn(Point2D pointOnTarget) { Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } GesturePane(Transformable target); GesturePane(Node target); GesturePane(); @Override String getUserAgentStylesheet(); Point2D viewportCentre(); Point2D targetPointAtViewportCentre(); Optional<Point2D> targetPointAt(Point2D viewportPoint); Point2D viewportPointAt(Point2D targetPoint); @Override void translateBy(Dimension2D targetAmount); @Override void centreOn(Point2D pointOnTarget); @Override void centreOnX(double pointOnTarget); @Override void centreOnY(double pointOnTarget); @Override void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget); @Override void zoomToX(double scaleX, Point2D pivotOnTarget); @Override void zoomToY(double scaleY, Point2D pivotOnTarget); @Override void zoomBy(double amountX,double amountY, Point2D pivotOnTarget); @Override void zoomByX(double amountX, Point2D pivotOnTarget); @Override void zoomByY(double amountY, Point2D pivotOnTarget); AnimationInterpolatorBuilder animate(Duration duration); final void reset(); void cover(); double getTargetWidth(); double getTargetHeight(); double getViewportWidth(); double getViewportHeight(); Bounds getViewportBound(); ReadOnlyObjectProperty<Bounds> viewportBoundProperty(); Transformable getTarget(); ObjectProperty<Transformable> targetProperty(); void setTarget(Transformable target); Node getContent(); ObjectProperty<Node> contentProperty(); void setContent(Node content); ScrollBarPolicy getVbarPolicy(); ObjectProperty<ScrollBarPolicy> vbarPolicyProperty(); void setVbarPolicy(ScrollBarPolicy policy); ScrollBarPolicy getHbarPolicy(); ObjectProperty<ScrollBarPolicy> hbarPolicyProperty(); void setHbarPolicy(ScrollBarPolicy policy); void setScrollBarPolicy(ScrollBarPolicy policy); boolean isChanging(); ReadOnlyBooleanProperty changingProperty(); boolean isGestureEnabled(); BooleanProperty gestureEnabledProperty(); void setGestureEnabled(boolean enable); boolean isClipEnabled(); BooleanProperty clipEnabledProperty(); void setClipEnabled(boolean enable); boolean isFitWidth(); BooleanProperty fitWidthProperty(); void setFitWidth(boolean fitWidth); boolean isFitHeight(); BooleanProperty fitHeightProperty(); void setFitHeight(boolean fitHeight); FitMode getFitMode(); ObjectProperty<FitMode> fitModeProperty(); void setFitMode(FitMode mode); ScrollMode getScrollMode(); ObjectProperty<ScrollMode> scrollModeProperty(); void setScrollMode(ScrollMode mode); boolean isInvertScrollTranslate(); BooleanProperty invertScrollTranslateProperty(); void setInvertScrollTranslate(boolean invertScrollTranslate); boolean isLockScaleX(); BooleanProperty lockScaleXProperty(); void setLockScaleX(boolean lockScaleX); boolean isLockScaleY(); BooleanProperty lockScaleYProperty(); void setLockScaleY(boolean lockScaleY); double getCurrentScale(); DoubleProperty currentScaleProperty(); boolean isBindScale(); BooleanProperty bindScaleProperty(); void setBindScale(boolean bindScale); double getMinScale(); DoubleProperty minScaleProperty(); void setMinScale(double scale); double getMaxScale(); DoubleProperty maxScaleProperty(); void setMaxScale(double scale); double getCurrentScaleX(); DoubleProperty currentScaleXProperty(); double getCurrentScaleY(); DoubleProperty currentScaleYProperty(); double getCurrentX(); DoubleBinding currentXProperty(); double getCurrentY(); DoubleBinding currentYProperty(); double getScrollZoomFactor(); DoubleProperty scrollZoomFactorProperty(); void setScrollZoomFactor(double factor); Bounds getTargetViewport(); ObjectProperty<Bounds> targetViewportProperty(); Affine getAffine(); @Override Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters); static final double DEFAULT_MIN_SCALE; static final double DEFAULT_MAX_SCALE; static final double DEFAULT_ZOOM_FACTOR; }
@Test public void testExtractAuthorFromDirectoryName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); File parent = createMock(File.class); expect(mock.getParentFile()).andReturn(parent); expect(parent.getName()).andReturn("Christopher, Matt"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new ParentDirectoryAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, hasItems(new Author("Matt", "Christopher"))); assertThat(authorScores.getScore(), is(1.0)); }
@NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
@Test public void testExtractMultipleAuthorsFromDirectoryName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); File parent = createMock(File.class); expect(mock.getParentFile()).andReturn(parent); expect(parent.getName()).andReturn("Jacques, Brian & Chalk, Gary"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new ParentDirectoryAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); double value = authorScores.getScore(); verifyAll(); assertThat(authors, hasItems(new Author("Brian", "Jacques"), new Author("Gary", "Chalk"))); assertThat(authorScores.getScore(), is(1.0)); }
@NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
ParentDirectoryAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { File file = context.getFile(); String dirName = file.getParentFile().getName(); String[] rawTokens = splitAuthorPairTokens(dirName); String[] tokens = trim(rawTokens); List<Author> authors = new ArrayList<>(); for (String token : tokens) { String[] rawNameTokens = splitAuthorNameTokens(token); String[] nameTokens = trim(rawNameTokens); if (nameTokens.length == 2) { Name name = new PersonNameCategorizer().categorize(nameTokens); Author author = new Author(name.getFirstName(), name.getLastName()); authors.add(author); } } return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
@Test public void testExtractAuthorFromFileName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("Abbott, Megan - Dare Me.epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, contains(new Author("Megan", "Abbott"))); assertThat(authorScores.getScore(), is(1.0)); }
private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); } }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); } }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); } @NotNull @Override AuthorScore score(BookImportContext context); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }
@Test public void testExtractAuthorFromOtherFileName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("P. L. Travers - Mary Poppins From A to Z(epub).epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, hasItems(new Author("P. L.", "Travers"))); assertThat(authorScores.getScore(), is(1.0)); }
@NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } @NotNull @Override AuthorScore score(BookImportContext context); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }
@Test public void testExtractAuthorFromOnlyLastname() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("Travers - Mary Poppins From A to Z(epub).epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); double value = authorScores.getScore(); verifyAll(); assertThat(authors, hasItems(new Author("", "Travers"))); assertThat(authorScores.getScore(), is(1.0)); }
@NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } @NotNull @Override AuthorScore score(BookImportContext context); }
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }
@Test public void extractAuthorFromMetaData() { File file = new File("src/test/resources/epubs/Alexandre Dumas - The countess of Charney.epub"); BookImportContext bookImportContext = new BookImportContext(file); Score<List<Author>> authorScores = new MetaDataAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); assertThat(authors, hasItems(new Author("Alexandre", "Dumas"))); assertThat(authorScores.getScore(), is(1.0)); }
@NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } }
MetaDataAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } } }
MetaDataAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } } }
MetaDataAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
MetaDataAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }
@Test public void testIsbn() { MetaDataIsbn13ScoreStrategy strategy = new MetaDataIsbn13ScoreStrategy(); BookImportContext importContext = new BookBuilder().isbn("1234567890123").buildContext(); Isbn13Score score = strategy.score(importContext); assertThat(score.getValue(), is("1234567890123")); assertThat(score.getScore(), is(1.0)); }
@NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; }
MetaDataIsbn13ScoreStrategy implements ScoreStrategy<Isbn13Score> { @NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; } }
MetaDataIsbn13ScoreStrategy implements ScoreStrategy<Isbn13Score> { @NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; } }
MetaDataIsbn13ScoreStrategy implements ScoreStrategy<Isbn13Score> { @NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; } @NotNull @Override Isbn13Score score(BookImportContext context); }
MetaDataIsbn13ScoreStrategy implements ScoreStrategy<Isbn13Score> { @NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; } @NotNull @Override Isbn13Score score(BookImportContext context); static final int ISBN_LENGTH; }
@Test public void testIsbn() { MetaDataIsbn10ScoreStrategy strategy = new MetaDataIsbn10ScoreStrategy(); BookImportContext importContext = new BookBuilder().isbn("1234567890").buildContext(); Isbn10Score score = strategy.score(importContext); assertThat(score.getValue(), is("1234567890")); assertThat(score.getScore(), is(1.0)); }
@NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; }
MetaDataIsbn10ScoreStrategy implements ScoreStrategy<Isbn10Score> { @NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; } }
MetaDataIsbn10ScoreStrategy implements ScoreStrategy<Isbn10Score> { @NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; } }
MetaDataIsbn10ScoreStrategy implements ScoreStrategy<Isbn10Score> { @NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; } @NotNull @Override Isbn10Score score(BookImportContext context); }
MetaDataIsbn10ScoreStrategy implements ScoreStrategy<Isbn10Score> { @NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; } @NotNull @Override Isbn10Score score(BookImportContext context); static final int ISBN_LENGTH; }