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 testSetName() { widget.setName("John", "Smith"); verify(widget.name).setText("John Smith"); } | public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } |
@Test public void shouldFailForAmbiguousProviders() { GwtMockito.useProviderForType(AnotherInterface.class, new FakeProvider<AnotherInterface>() { @Override public AnotherInterface getFake(Class<?> type) { return mock(AnotherInterface.class); } }); GwtMockito.useProviderForType(YetAnotherInterface.class, new FakeProvider<YetAnotherInterface>() { @Override public YetAnotherInterface getFake(Class<?> type) { return mock(YetAnotherInterface.class); } }); try { GWT.create(AmbiguousInterface.class); fail("Exception not thrown"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("AmbiguousInterface")); assertTrue(e.getMessage().contains("AnotherInterface")); assertTrue(e.getMessage().contains("YetAnotherInterface")); } } | public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void getFakeShouldReturnDefaultFakes() { SampleMessages messages = GwtMockito.getFake(SampleMessages.class); assertEquals("noArgs", messages.noArgs()); } | public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void getFakeShouldFailForUnregisteredFakes() { try { GwtMockito.getFake(SampleInterface.class); fail("Exception not thrown"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("SampleInterface")); } } | public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void testUpdateData() { when(dataProvider.getData()).thenReturn("data"); widget.updateData(); verify(widget.data).setText("data"); } | public void updateData() { data.setText(dataProvider.getData()); } | MyWidget extends Composite { public void updateData() { data.setText(dataProvider.getData()); } } | MyWidget extends Composite { public void updateData() { data.setText(dataProvider.getData()); } MyWidget(); } | MyWidget extends Composite { public void updateData() { data.setText(dataProvider.getData()); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } | MyWidget extends Composite { public void updateData() { data.setText(dataProvider.getData()); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } |
@Test public void testSetNameWithFakes() { GwtMockito.useProviderForType(HasText.class, new FakeProvider<HasText>() { @Override public HasText getFake(Class<?> type) { return new HasText() { private String text; @Override public void setText(String text) { this.text = text; } @Override public String getText() { return text; } }; } }); widget = new MyWidget(); widget.setName("John", "Smith"); assertEquals("John Smith", widget.name.getText()); } | public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } | MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } |
@Test @SuppressWarnings("unchecked") public void testMockRpcs() { doAnswer(returnSuccess("some data")).when(myService).getData(any(AsyncCallback.class)); widget.loadDataFromRpc(); verify(widget.data).setText("some data"); } | public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } | MyWidget extends Composite { public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } } | MyWidget extends Composite { public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } MyWidget(); } | MyWidget extends Composite { public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } | MyWidget extends Composite { public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); } |
@Test public void canUseProvidersForTypes() { GwtMockito.useProviderForType(AnotherInterface.class, new FakeProvider<AnotherInterface>() { @Override public AnotherInterface getFake(Class<?> type) { return new AnotherInterface() { @Override public String doSomethingElse() { return "some value"; } }; } }); AnotherInterface result = GWT.create(AnotherInterface.class); assertEquals("some value", result.doSomethingElse()); } | public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void typeProvidersShouldWorkForSubtypes() { final Widget someWidget = mock(Widget.class); GwtMockito.useProviderForType(Widget.class, new FakeProvider<Widget>() { @Override public Widget getFake(Class<?> type) { assertTrue(type == Label.class); return someWidget; } }); assertSame(someWidget, GWT.create(Label.class)); } | public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test(expected = IllegalArgumentException.class) public void shouldNotAllowProvidersForGwtMockedTypes() { GwtMockito.useProviderForType(SampleInterface.class, new FakeProvider<SampleInterface>() { @Override public SampleInterface getFake(Class<?> type) { return mock(SampleInterface.class); } }); } | public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test(expected = IllegalArgumentException.class) public void shouldNotAllowMultipleGwtMocksForSameType() { GwtMockito.initMocks(new Object() { @GwtMock SampleInterface mock1; @GwtMock SampleInterface mock2; }); } | public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.initMocks(owner); success = true; } finally { if (!success) { tearDown(); } } } | GwtMockito { public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.initMocks(owner); success = true; } finally { if (!success) { tearDown(); } } } } | GwtMockito { public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.initMocks(owner); success = true; } finally { if (!success) { tearDown(); } } } } | GwtMockito { public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.initMocks(owner); success = true; } finally { if (!success) { tearDown(); } } } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.initMocks(owner); success = true; } finally { if (!success) { tearDown(); } } } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void canUseProvidersForDifferentTypes() { GwtMockito.useProviderForType(Button.class, new FakeProvider<Label>() { @Override public Label getFake(Class<?> type) { Label label = mock(Label.class); when(label.getText()).thenReturn("abc"); return label; } }); Label label = GWT.create(Button.class); assertEquals("abc", label.getText()); } | public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void shouldAlwaysUseMostSpecificProvider() { GwtMockito.useProviderForType(AnotherInterface.class, new FakeProvider<AnotherInterface>() { @Override public AnotherInterface getFake(Class<?> type) { AnotherInterface mock = (AnotherInterface) mock(type); when(mock.doSomethingElse()).thenReturn("anotherInterface"); return mock; } }); SubSubInterface i = GWT.create(SubSubInterface.class); assertEquals("anotherInterface", i.doSomethingElse()); GwtMockito.useProviderForType(SubInterface.class, new FakeProvider<SubInterface>() { @Override public SubInterface getFake(Class<?> type) { SubInterface mock = (SubInterface) mock(type); when(mock.doSomethingElse()).thenReturn("subInterface"); return mock; } }); i = GWT.create(SubSubInterface.class); assertEquals("subInterface", i.doSomethingElse()); GwtMockito.useProviderForType(SubSubInterface.class, new FakeProvider<SubSubInterface>() { @Override public SubSubInterface getFake(Class<?> type) { SubSubInterface mock = (SubSubInterface) mock(type); when(mock.doSomethingElse()).thenReturn("subSubInterface"); return mock; } }); i = GWT.create(SubSubInterface.class); assertEquals("subSubInterface", i.doSomethingElse()); } | public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } | GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider for a type that already has a @GwtMock declared"); } bridge.registeredProviders.put(type, provider); } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); } |
@Test public void shouldWriteDoBindEventHandler() throws Exception { JClassType eventType1 = getEventType(MyEvent1.class); JClassType eventType2 = getEventType(MyEvent2.class); JMethod method1 = newMethod("method1", eventType1); JMethod method2 = newMethod("method2", eventType2); JMethod method3 = newMethod("method3", new JType[] {genericEventType}, new Class[] {MyEvent1.class, MyEvent2.class}); JMethod method4 = newMethod("method4", new JType[] {}, new Class[] {MyEvent1.class}); when(target.getQualifiedSourceName()).thenReturn("MyTarget"); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method1, method2, method3, method4}); writer.writeDoBindEventHandlers(target, output, typeOracle); assertEquals(join( "protected List<HandlerRegistration> doBindEventHandlers(" + "final MyTarget target, EventBus eventBus) {", " List<HandlerRegistration> registrations = new LinkedList<HandlerRegistration>();", " bind(eventBus, registrations, " + className(MyEvent1.class) + ".class, new GenericEventHandler() {", " public void handleEvent(GenericEvent event) { target.method1((" + className(MyEvent1.class) + ") event); }", " });", " bind(eventBus, registrations, " + className(MyEvent2.class) +".class, new GenericEventHandler() {", " public void handleEvent(GenericEvent event) { target.method2((" + className(MyEvent2.class) + ") event); }", " });", " bind(eventBus, registrations, " + className(MyEvent1.class) + ".class, new GenericEventHandler() {", " public void handleEvent(GenericEvent event) { target.method3((" + className(MyEvent1.class) +") event); }", " });", " bind(eventBus, registrations, " + className(MyEvent2.class) + ".class, new GenericEventHandler() {", " public void handleEvent(GenericEvent event) { target.method3((" + className(MyEvent2.class) + ") event); }", " });", " bind(eventBus, registrations, " + className(MyEvent1.class) + ".class, new GenericEventHandler() {", " public void handleEvent(GenericEvent event) { target.method4(); }", " });", " return registrations;", "}"), output.toString()); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void shouldFailOnZeroParametersWithoutEvents() throws Exception { JMethod method = newMethod("myMethod"); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method}); try { writer.writeDoBindEventHandlers(target, output, typeOracle); fail("Exception not thrown"); } catch (UnableToCompleteException expected) {} verify(logger).log( eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class)); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void shouldFailOnTwoParameters() throws Exception { JMethod method = newMethod("myMethod", mock(JType.class), mock(JType.class)); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method}); try { writer.writeDoBindEventHandlers(target, output, typeOracle); fail("Exception not thrown"); } catch (UnableToCompleteException expected) {} verify(logger).log( eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class)); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void shouldFailOnInvalidParameter() throws Exception { JClassType paramType = mock(JClassType.class); when(paramType.isAssignableTo(genericEventType)).thenReturn(false); when(paramType.isClassOrInterface()).thenReturn(paramType); JMethod method = newMethod("myMethod", paramType); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method}); try { writer.writeDoBindEventHandlers(target, output, typeOracle); fail("Exception not thrown"); } catch (UnableToCompleteException expected) {} verify(logger).log( eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class)); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void shouldFailForEventWhichIsNotAssignableToParameter() throws Exception { JClassType eventType1 = getEventType(MyEvent1.class); JMethod method = newMethod("myMethod", new JType[] {eventType1}, new Class[] {MyEvent2.class}); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method}); try { writer.writeDoBindEventHandlers(target, output, typeOracle); fail("Exception not thrown"); } catch (UnableToCompleteException expected) {} verify(logger).log( eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class)); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void shouldFailOnPrimitiveParameter() throws Exception { JClassType paramType = mock(JClassType.class); when(paramType.isClassOrInterface()).thenReturn(null); JMethod method = newMethod("myMethod", paramType); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method}); try { writer.writeDoBindEventHandlers(target, output, typeOracle); fail("Exception not thrown"); } catch (UnableToCompleteException expected) {} verify(logger).log( eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class)); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void shouldFailOnAbstractParameter() throws Exception { JClassType paramType = getEventType(AbstractEvent.class); when(paramType.isAbstract()).thenReturn(true); JMethod method = newMethod("myMethod", paramType); when(target.getInheritableMethods()).thenReturn(new JMethod[] {method}); try { writer.writeDoBindEventHandlers(target, output, typeOracle); fail("Exception not thrown"); } catch (UnableToCompleteException expected) {} verify(logger).log( eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class)); } | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } | EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(EventHandler.class); if (annotation != null) { writeHandlerForBindMethod(annotation, writer, method, typeOracle); } } writeBindMethodFooter(writer); } EventBinderWriter(TreeLogger logger, JClassType genericEventType); } |
@Test public void testRegister() throws Exception { final LeaseInfo leaseInfo = getLeaseInfo(); final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, leaseInfo); instanceRegistry.register(instanceInfo, false); assertEquals(1, this.testEvents.applicationEvents.size()); assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRegisteredEvent); final EurekaInstanceRegisteredEvent registeredEvent = (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0)); assertEquals(instanceInfo, registeredEvent.getInstanceInfo()); assertEquals(leaseInfo.getDurationInSecs(), registeredEvent.getLeaseDuration()); assertEquals(instanceRegistry, registeredEvent.getSource()); assertFalse(registeredEvent.isReplication()); } | @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } |
@Test public void testDefaultLeaseDurationRegisterEvent() throws Exception { final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); instanceRegistry.register(instanceInfo, false); final EurekaInstanceRegisteredEvent registeredEvent = (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0)); assertEquals(LeaseInfo.DEFAULT_LEASE_DURATION, registeredEvent.getLeaseDuration()); } | @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } |
@Test public void testInternalCancel() throws Exception { instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false); assertEquals(1, this.testEvents.applicationEvents.size()); assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceCanceledEvent); final EurekaInstanceCanceledEvent registeredEvent = (EurekaInstanceCanceledEvent) (this.testEvents.applicationEvents.get(0)); assertEquals(APP_NAME, registeredEvent.getAppName()); assertEquals(HOST_NAME, registeredEvent.getServerId()); assertEquals(instanceRegistry, registeredEvent.getSource()); assertFalse(registeredEvent.isReplication()); } | @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } |
@Test public void testRenew() throws Exception { final InstanceInfo instanceInfo1 = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); final InstanceInfo instanceInfo2 = getInstanceInfo(APP_NAME, HOST_NAME, "my-host-name:8009", 8009, null); final Application application = new Application(APP_NAME, Arrays.asList(instanceInfo1, instanceInfo2)); final List<Application> applications = new ArrayList<>(); applications.add(application); doReturn(applications).when(instanceRegistry).getSortedApplications(); instanceRegistry.renew(APP_NAME, INSTANCE_ID, false); instanceRegistry.renew(APP_NAME, "my-host-name:8009", false); assertEquals(2, this.testEvents.applicationEvents.size()); assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRenewedEvent); assertTrue(this.testEvents.applicationEvents.get(1) instanceof EurekaInstanceRenewedEvent); final EurekaInstanceRenewedEvent event1 = (EurekaInstanceRenewedEvent) (this.testEvents.applicationEvents.get(0)); assertEquals(APP_NAME, event1.getAppName()); assertEquals(INSTANCE_ID, event1.getServerId()); assertEquals(instanceRegistry, event1.getSource()); assertEquals(instanceInfo1, event1.getInstanceInfo()); assertFalse(event1.isReplication()); final EurekaInstanceRenewedEvent event2 = (EurekaInstanceRenewedEvent) (this.testEvents.applicationEvents.get(1)); assertEquals(instanceInfo2, event2.getInstanceInfo()); } | @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { log("renew " + appName + " serverId " + serverId + ", isReplication {}" + isReplication); List<Application> applications = getSortedApplications(); for (Application input : applications) { if (input.getName().equals(appName)) { InstanceInfo instance = null; for (InstanceInfo info : input.getInstances()) { if (info.getId().equals(serverId)) { instance = info; break; } } publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, instance, isReplication)); break; } } return super.renew(appName, serverId, isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { log("renew " + appName + " serverId " + serverId + ", isReplication {}" + isReplication); List<Application> applications = getSortedApplications(); for (Application input : applications) { if (input.getName().equals(appName)) { InstanceInfo instance = null; for (InstanceInfo info : input.getInstances()) { if (info.getId().equals(serverId)) { instance = info; break; } } publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, instance, isReplication)); break; } } return super.renew(appName, serverId, isReplication); } } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { log("renew " + appName + " serverId " + serverId + ", isReplication {}" + isReplication); List<Application> applications = getSortedApplications(); for (Application input : applications) { if (input.getName().equals(appName)) { InstanceInfo instance = null; for (InstanceInfo info : input.getInstances()) { if (info.getId().equals(serverId)) { instance = info; break; } } publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, instance, isReplication)); break; } } return super.renew(appName, serverId, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { log("renew " + appName + " serverId " + serverId + ", isReplication {}" + isReplication); List<Application> applications = getSortedApplications(); for (Application input : applications) { if (input.getName().equals(appName)) { InstanceInfo instance = null; for (InstanceInfo info : input.getInstances()) { if (info.getId().equals(serverId)) { instance = info; break; } } publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, instance, isReplication)); break; } } return super.renew(appName, serverId, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } | InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { log("renew " + appName + " serverId " + serverId + ", isReplication {}" + isReplication); List<Application> applications = getSortedApplications(); for (Application input : applications) { if (input.getName().equals(appName)) { InstanceInfo instance = null; for (InstanceInfo info : input.getInstances()) { if (info.getId().equals(serverId)) { instance = info; break; } } publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, instance, isReplication)); break; } } return super.renew(appName, serverId, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); } |
@Test public void testStatus() throws Exception { Map<String, Object> model = new HashMap<>(); EurekaController controller = new EurekaController(infoManager); controller.status(new MockHttpServletRequest("GET", "/"), model); Map<String, Object> app = getFirst(model, "apps"); Map<String, Object> instanceInfo = getFirst(app, "instanceInfos"); Map<String, Object> instance = getFirst(instanceInfo, "instances"); assertThat("id was wrong", (String)instance.get("id"), is(equalTo("myapp:1"))); assertThat("url was not null", instance.get("url"), is(nullValue())); assertThat("isHref was wrong", (Boolean)instance.get("isHref"), is(false)); } | @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); } model.put("statusInfo", statusInfo); populateInstanceInfo(model, statusInfo); filterReplicas(model, statusInfo); return "eureka/status"; } | EurekaController { @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); } model.put("statusInfo", statusInfo); populateInstanceInfo(model, statusInfo); filterReplicas(model, statusInfo); return "eureka/status"; } } | EurekaController { @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); } model.put("statusInfo", statusInfo); populateInstanceInfo(model, statusInfo); filterReplicas(model, statusInfo); return "eureka/status"; } EurekaController(ApplicationInfoManager applicationInfoManager); } | EurekaController { @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); } model.put("statusInfo", statusInfo); populateInstanceInfo(model, statusInfo); filterReplicas(model, statusInfo); return "eureka/status"; } EurekaController(ApplicationInfoManager applicationInfoManager); @RequestMapping(method = RequestMethod.GET) String status(HttpServletRequest request, Map<String, Object> model); @RequestMapping(value = "/lastn", method = RequestMethod.GET) String lastn(HttpServletRequest request, Map<String, Object> model); } | EurekaController { @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); } model.put("statusInfo", statusInfo); populateInstanceInfo(model, statusInfo); filterReplicas(model, statusInfo); return "eureka/status"; } EurekaController(ApplicationInfoManager applicationInfoManager); @RequestMapping(method = RequestMethod.GET) String status(HttpServletRequest request, Map<String, Object> model); @RequestMapping(value = "/lastn", method = RequestMethod.GET) String lastn(HttpServletRequest request, Map<String, Object> model); } |
@Test public void get() throws Exception { Response response = HttpClient.getInstance().get("http: System.out.println(response); } | public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } | HttpClient { public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } } | HttpClient { public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } private HttpClient(); } | HttpClient { public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); } | HttpClient { public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); } |
@Test public void getAnnotatedClasses() { ClassUtils.getAnnotatedClasses("com.timeyang.search.entity", Document.class).forEach(System.out::println); } | public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } | ClassUtils { public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } } | ClassUtils { public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } } | ClassUtils { public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation); } | ClassUtils { public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation); } |
@Test public void convertToString() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("settings", new JSONObject().put("index", new JSONObject().put("number_of_shards", 3) .put("number_of_replicas", 2) ) ); String settings = JsonUtils.convertToString(jsonObject); System.out.println(settings); } | public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } | JsonUtils { public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } | JsonUtils { public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } | JsonUtils { public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } static String convertToString(JSONObject jsonObject); static byte[] convertToBytes(JSONObject jsonObject); static JSONObject readValue(InputStream inputStream); static T parseJsonToObject(String json, Class<T> clazz); } | JsonUtils { public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } static String convertToString(JSONObject jsonObject); static byte[] convertToBytes(JSONObject jsonObject); static JSONObject readValue(InputStream inputStream); static T parseJsonToObject(String json, Class<T> clazz); } |
@Test public void deleteConnector() throws Exception { JkesProperties jkesProperties = new DefaultJkesPropertiesImpl() { @Override public String getKafkaConnectServers() { return "http: } }; Config.setJkesProperties(jkesProperties); String connectorName = KafkaConnectUtils.getConnectorName(Person.class); new KafkaConnectClient(jkesProperties, new Metadata.MetadataBuilder(jkesProperties).build()).deleteConnector(connectorName); } | public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); HTTP_CLIENT.delete(url, endpoint); }finally { locks.get(connectorName).unlock(); } } catch (IOException e) { throw new KafkaConnectRequestException(e); } } | KafkaConnectClient { public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); HTTP_CLIENT.delete(url, endpoint); }finally { locks.get(connectorName).unlock(); } } catch (IOException e) { throw new KafkaConnectRequestException(e); } } } | KafkaConnectClient { public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); HTTP_CLIENT.delete(url, endpoint); }finally { locks.get(connectorName).unlock(); } } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); } | KafkaConnectClient { public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); HTTP_CLIENT.delete(url, endpoint); }finally { locks.get(connectorName).unlock(); } } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); JSONObject getConnectConfig(String connectorName); boolean createIndexSinkConnectorIfAbsent(Class<?> document); void updateIndexSinkConnector(Class<?> document); boolean createDeleteSinkConnectorIfAbsent(); boolean ensureEsSinkConnector(Class<?> document); void deleteConnector(String connectorName); void restartConnector(String connectorName); boolean checkConnectorExists(String connectorName); } | KafkaConnectClient { public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); HTTP_CLIENT.delete(url, endpoint); }finally { locks.get(connectorName).unlock(); } } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); JSONObject getConnectConfig(String connectorName); boolean createIndexSinkConnectorIfAbsent(Class<?> document); void updateIndexSinkConnector(Class<?> document); boolean createDeleteSinkConnectorIfAbsent(); boolean ensureEsSinkConnector(Class<?> document); void deleteConnector(String connectorName); void restartConnector(String connectorName); boolean checkConnectorExists(String connectorName); } |
@Test public void checkConnectorExists() throws Exception { JkesProperties jkesProperties = new DefaultJkesPropertiesImpl() { @Override public String getKafkaConnectServers() { return "http: } }; Config.setJkesProperties(jkesProperties); String connectorName = KafkaConnectUtils.getConnectorName(Person.class); System.out.println(new KafkaConnectClient(jkesProperties, new Metadata.MetadataBuilder(jkesProperties).build()).checkConnectorExists(connectorName)); } | public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint); }finally { locks.get(connectorName).unlock(); } boolean contain = (response.getStatusCode() / 100) == 2; return contain; } catch (IOException e) { throw new KafkaConnectRequestException(e); } } | KafkaConnectClient { public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint); }finally { locks.get(connectorName).unlock(); } boolean contain = (response.getStatusCode() / 100) == 2; return contain; } catch (IOException e) { throw new KafkaConnectRequestException(e); } } } | KafkaConnectClient { public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint); }finally { locks.get(connectorName).unlock(); } boolean contain = (response.getStatusCode() / 100) == 2; return contain; } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); } | KafkaConnectClient { public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint); }finally { locks.get(connectorName).unlock(); } boolean contain = (response.getStatusCode() / 100) == 2; return contain; } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); JSONObject getConnectConfig(String connectorName); boolean createIndexSinkConnectorIfAbsent(Class<?> document); void updateIndexSinkConnector(Class<?> document); boolean createDeleteSinkConnectorIfAbsent(); boolean ensureEsSinkConnector(Class<?> document); void deleteConnector(String connectorName); void restartConnector(String connectorName); boolean checkConnectorExists(String connectorName); } | KafkaConnectClient { public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint); }finally { locks.get(connectorName).unlock(); } boolean contain = (response.getStatusCode() / 100) == 2; return contain; } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); JSONObject getConnectConfig(String connectorName); boolean createIndexSinkConnectorIfAbsent(Class<?> document); void updateIndexSinkConnector(Class<?> document); boolean createDeleteSinkConnectorIfAbsent(); boolean ensureEsSinkConnector(Class<?> document); void deleteConnector(String connectorName); void restartConnector(String connectorName); boolean checkConnectorExists(String connectorName); } |
@Test public void buildIndex() throws Exception { IndicesBuilder indicesBuilder = IndicesBuilder.getInstance(); JSONObject indices = indicesBuilder.buildIndex(PersonGroup.class); System.out.println(JsonUtils.convertToString(indices)); } | public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); JSONObject mappings = new JSONObject(); JSONObject mapping = new MappingBuilder().buildMapping(clazz); String type = DocumentUtils.getTypeName(clazz); mappings.put(type, mapping); JSONObject aliases = new JSONObject(); aliases.put(DocumentUtils.getAlias(clazz), new JSONObject()); JSONObject indices = new JSONObject(); indices.put("settings", settings); indices.put("mappings", mappings); indices.put("aliases", aliases); return indices; } | IndicesBuilder { public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); JSONObject mappings = new JSONObject(); JSONObject mapping = new MappingBuilder().buildMapping(clazz); String type = DocumentUtils.getTypeName(clazz); mappings.put(type, mapping); JSONObject aliases = new JSONObject(); aliases.put(DocumentUtils.getAlias(clazz), new JSONObject()); JSONObject indices = new JSONObject(); indices.put("settings", settings); indices.put("mappings", mappings); indices.put("aliases", aliases); return indices; } } | IndicesBuilder { public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); JSONObject mappings = new JSONObject(); JSONObject mapping = new MappingBuilder().buildMapping(clazz); String type = DocumentUtils.getTypeName(clazz); mappings.put(type, mapping); JSONObject aliases = new JSONObject(); aliases.put(DocumentUtils.getAlias(clazz), new JSONObject()); JSONObject indices = new JSONObject(); indices.put("settings", settings); indices.put("mappings", mappings); indices.put("aliases", aliases); return indices; } private IndicesBuilder(); } | IndicesBuilder { public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); JSONObject mappings = new JSONObject(); JSONObject mapping = new MappingBuilder().buildMapping(clazz); String type = DocumentUtils.getTypeName(clazz); mappings.put(type, mapping); JSONObject aliases = new JSONObject(); aliases.put(DocumentUtils.getAlias(clazz), new JSONObject()); JSONObject indices = new JSONObject(); indices.put("settings", settings); indices.put("mappings", mappings); indices.put("aliases", aliases); return indices; } private IndicesBuilder(); JSONObject buildIndex(Class<?> clazz); static IndicesBuilder getInstance(); } | IndicesBuilder { public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); JSONObject mappings = new JSONObject(); JSONObject mapping = new MappingBuilder().buildMapping(clazz); String type = DocumentUtils.getTypeName(clazz); mappings.put(type, mapping); JSONObject aliases = new JSONObject(); aliases.put(DocumentUtils.getAlias(clazz), new JSONObject()); JSONObject indices = new JSONObject(); indices.put("settings", settings); indices.put("mappings", mappings); indices.put("aliases", aliases); return indices; } private IndicesBuilder(); JSONObject buildIndex(Class<?> clazz); static IndicesBuilder getInstance(); } |
@Test public void start() throws Exception { indicesAdminClient.init(); } | @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz); } } logger.info("search init finished"); } | IndicesAdminClient { @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz); } } logger.info("search init finished"); } } | IndicesAdminClient { @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz); } } logger.info("search init finished"); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); } | IndicesAdminClient { @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz); } } logger.info("search init finished"); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); } | IndicesAdminClient { @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz); } } logger.info("search init finished"); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); } |
@Test public void createIndex() throws Exception { if(!indicesAdminClient.checkExists("my_index")) indicesAdminClient.createIndex(PersonGroup.class); } | public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get(indexName).unlock(); logger.info("created index[" + indexName + "] for entity: " + clazz); } | IndicesAdminClient { public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get(indexName).unlock(); logger.info("created index[" + indexName + "] for entity: " + clazz); } } | IndicesAdminClient { public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get(indexName).unlock(); logger.info("created index[" + indexName + "] for entity: " + clazz); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); } | IndicesAdminClient { public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get(indexName).unlock(); logger.info("created index[" + indexName + "] for entity: " + clazz); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); } | IndicesAdminClient { public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get(indexName).unlock(); logger.info("created index[" + indexName + "] for entity: " + clazz); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); } |
@Test public void checkExists() throws Exception { indicesAdminClient.checkExists("my_index"); } | public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } | IndicesAdminClient { public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } } | IndicesAdminClient { public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); } | IndicesAdminClient { public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); } | IndicesAdminClient { public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); } |
@Test public void buildMapping() { JSONObject mapping = new MappingBuilder().buildMapping(PersonGroup.class); System.out.println(JsonUtils.convertToString(mapping)); } | public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } | MappingBuilder { public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } } | MappingBuilder { public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } } | MappingBuilder { public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } JSONObject buildMapping(Class<?> clazz); } | MappingBuilder { public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } JSONObject buildMapping(Class<?> clazz); } |
@Test public void post() throws Exception { } | public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } | HttpClient { public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } } | HttpClient { public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } private HttpClient(); } | HttpClient { public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); } | HttpClient { public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); } |
@Test public void buildUri() throws Exception { String url = "http: InetAddress address = InetAddress.getByName(new URL(url).getHost()); String ip = address.getHostAddress(); System.out.println(ip); } | static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } | HttpClient { static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } } | HttpClient { static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } private HttpClient(); } | HttpClient { static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); } | HttpClient { static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); } |
@Test public void parseIpFromUrl() throws Exception { System.out.println(HttpUtils.parseIpFromUrl("http: } | public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } | HttpUtils { public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } } | HttpUtils { public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } } | HttpUtils { public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); } | HttpUtils { public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); } |
@Test public void getIpsFormUrls() throws Exception { System.out.println(Arrays.toString(HttpUtils.getIpsFromUrls("http: } | public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } return ips; } | HttpUtils { public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } return ips; } } | HttpUtils { public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } return ips; } } | HttpUtils { public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } return ips; } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); } | HttpUtils { public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } return ips; } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); } |
@Test public void getIpsFormDomainNames() throws Exception { System.out.println(Arrays.toString(HttpUtils.getIpsFromDomainNames("timeyang.com", "github.com"))); } | public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return ips; } | HttpUtils { public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return ips; } } | HttpUtils { public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return ips; } } | HttpUtils { public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return ips; } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); } | HttpUtils { public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return ips; } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); } |
@Test public void getReturnTypeParameters() throws Exception { Method method = PersonGroup.class.getDeclaredMethod("getPersons"); ReflectionUtils.getReturnTypeParameters(method); } | public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) { typeParameters.add(m.group(2)); } return typeParameters; } | ReflectionUtils { public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) { typeParameters.add(m.group(2)); } return typeParameters; } } | ReflectionUtils { public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) { typeParameters.add(m.group(2)); } return typeParameters; } } | ReflectionUtils { public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) { typeParameters.add(m.group(2)); } return typeParameters; } static List<String> getReturnTypeParameters(Method method); static String getTypeName(Method method); static String getInnermostType(Method method); static Class<?> getInnermostTypeClass(Method method); static String getInnermostType(Field field); static Class<?> getInnermostTypeClass(Field field); static String getFieldNameForGetter(String methodName); static String getFieldNameForGetter(Method method); static Object invokeMethod(Object target, String methodName, Class<?>[] parameterTypes, Object... params); static Object getAnnotatedFieldValue(Object target, Class<? extends Annotation> annotation); static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation); static T getFieldAnnotation(Class<?> clazz, String fieldName, Class<T> annotationClass); static Object getAnnotatedMethodReturnValue(Object target, Class<? extends Annotation> annotation); } | ReflectionUtils { public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) { typeParameters.add(m.group(2)); } return typeParameters; } static List<String> getReturnTypeParameters(Method method); static String getTypeName(Method method); static String getInnermostType(Method method); static Class<?> getInnermostTypeClass(Method method); static String getInnermostType(Field field); static Class<?> getInnermostTypeClass(Field field); static String getFieldNameForGetter(String methodName); static String getFieldNameForGetter(Method method); static Object invokeMethod(Object target, String methodName, Class<?>[] parameterTypes, Object... params); static Object getAnnotatedFieldValue(Object target, Class<? extends Annotation> annotation); static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation); static T getFieldAnnotation(Class<?> clazz, String fieldName, Class<T> annotationClass); static Object getAnnotatedMethodReturnValue(Object target, Class<? extends Annotation> annotation); } |
@Test public void getActualReturnType() throws Exception { Method method1 = ComplexEntity.class.getDeclaredMethod("getCars"); System.out.println(ReflectionUtils.getInnermostType(method1)); Method method2 = ComplexEntity.class.getDeclaredMethod("getBooks"); System.out.println(ReflectionUtils.getInnermostType(method2)); } | public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } | ReflectionUtils { public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } } | ReflectionUtils { public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } } | ReflectionUtils { public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } static List<String> getReturnTypeParameters(Method method); static String getTypeName(Method method); static String getInnermostType(Method method); static Class<?> getInnermostTypeClass(Method method); static String getInnermostType(Field field); static Class<?> getInnermostTypeClass(Field field); static String getFieldNameForGetter(String methodName); static String getFieldNameForGetter(Method method); static Object invokeMethod(Object target, String methodName, Class<?>[] parameterTypes, Object... params); static Object getAnnotatedFieldValue(Object target, Class<? extends Annotation> annotation); static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation); static T getFieldAnnotation(Class<?> clazz, String fieldName, Class<T> annotationClass); static Object getAnnotatedMethodReturnValue(Object target, Class<? extends Annotation> annotation); } | ReflectionUtils { public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } static List<String> getReturnTypeParameters(Method method); static String getTypeName(Method method); static String getInnermostType(Method method); static Class<?> getInnermostTypeClass(Method method); static String getInnermostType(Field field); static Class<?> getInnermostTypeClass(Field field); static String getFieldNameForGetter(String methodName); static String getFieldNameForGetter(Method method); static Object invokeMethod(Object target, String methodName, Class<?>[] parameterTypes, Object... params); static Object getAnnotatedFieldValue(Object target, Class<? extends Annotation> annotation); static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation); static T getFieldAnnotation(Class<?> clazz, String fieldName, Class<T> annotationClass); static Object getAnnotatedMethodReturnValue(Object target, Class<? extends Annotation> annotation); } |
@Test public void testGetClasses() throws IOException, ClassNotFoundException { Class[] classes = SimpleClassUtils.getClasses("com.timeyang.search.entity"); for (Class c : classes) { System.out.println(c); } for (Class c : SimpleClassUtils.getClasses("com.fasterxml.jackson.databind.module")) { System.out.println(c); } } | static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } | SimpleClassUtils { static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } } | SimpleClassUtils { static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } } | SimpleClassUtils { static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } } | SimpleClassUtils { static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } } |
@Test public void getCLasses() { ClassUtils.getClasses("com.timeyang.search.entity").forEach(System.out::println); ClassUtils.getClasses("com.fasterxml.jackson.databind.module").forEach(System.out::println); } | static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false ), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; } | ClassUtils { static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false ), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; } } | ClassUtils { static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false ), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; } } | ClassUtils { static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false ), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; } static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation); } | ClassUtils { static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false ), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; } static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation); } |
@Test public void testSQLExceptionUnwrap() { SQLTransactionRollbackException transactionRollbackException = new SQLTransactionRollbackException(); SQLRecoverableException recoverableException = new SQLRecoverableException(); SQLSyntaxErrorException syntaxErrorException = new SQLSyntaxErrorException(); recoverableException.setNextException(syntaxErrorException); transactionRollbackException.setNextException(recoverableException); Throwable e = new Exception(transactionRollbackException); ExceptionStack es = new ExceptionStack(e); assertThat(es.getCauseElements().size(), is(4)); assertThat(es.getCauseElements(), hasItems(e, transactionRollbackException, recoverableException, syntaxErrorException)); } | public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } | ExceptionStack implements Serializable { public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } } | ExceptionStack implements Serializable { public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } ExceptionStack(); ExceptionStack(final Throwable exception); @Deprecated protected ExceptionStack(final Collection<Throwable> causeChainElements, final int currentElementIndex); } | ExceptionStack implements Serializable { public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } ExceptionStack(); ExceptionStack(final Throwable exception); @Deprecated protected ExceptionStack(final Collection<Throwable> causeChainElements, final int currentElementIndex); Collection<Throwable> getCauseElements(); boolean isLast(); Throwable getNext(); Collection<Throwable> getRemaining(); boolean isRoot(); Throwable getCurrent(); void setCauseElements(Collection<Throwable> elements); Deque<ExceptionStackItem> getOrigExceptionStackItems(); } | ExceptionStack implements Serializable { public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } ExceptionStack(); ExceptionStack(final Throwable exception); @Deprecated protected ExceptionStack(final Collection<Throwable> causeChainElements, final int currentElementIndex); Collection<Throwable> getCauseElements(); boolean isLast(); Throwable getNext(); Collection<Throwable> getRemaining(); boolean isRoot(); Throwable getCurrent(); void setCauseElements(Collection<Throwable> elements); Deque<ExceptionStackItem> getOrigExceptionStackItems(); } |
@Test public void test(){ String sql = "select 1"; String text = route(sql); Assert.assertSame(text,""); } | public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } | RouteService { public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } } | RouteService { public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } RouteService(MetadataManager metadataManager); } | RouteService { public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } RouteService(MetadataManager metadataManager); static RouteService create(MetadataManager metadataManager); Schema route(String sql); } | RouteService { public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } RouteService(MetadataManager metadataManager); static RouteService create(MetadataManager metadataManager); Schema route(String sql); } |
@Test public void balanceExpand() { List<List<NodeIndexRange>> integerListMap = new ArrayList<>(); integerListMap.add(Lists.newArrayList(new NodeIndexRange(0, 0, 32))); integerListMap.add(Lists.newArrayList(new NodeIndexRange(1, 33, 65))); integerListMap.add(Lists.newArrayList(new NodeIndexRange(2, 66, 99))); int totalSlots = 100; List<String> oldDataNodes = Lists.newArrayList("dn1", "dn2", "dn3"); List<String> newDataNodes = Lists.newArrayList("dn4", "dn5"); SortedMap<String, List<MigrateTask>> tasks = MigrateUtils.balanceExpand(integerListMap, oldDataNodes, newDataNodes, totalSlots); Assert.assertEquals("{dn4=[MigrateTask{from='dn1'\n" + ", to='dn4'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=0, valueEnd=12)]\n" + "}, MigrateTask{from='dn2'\n" + ", to='dn4'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=33, valueEnd=39)]\n" + "}], dn5=[MigrateTask{from='dn2'\n" + ", to='dn5'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=40, valueEnd=45)]\n" + "}, MigrateTask{from='dn3'\n" + ", to='dn5'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=66, valueEnd=79)]\n" + "}]}", Objects.toString(tasks)); merge(integerListMap, tasks); oldDataNodes = Lists.newArrayList("dn1", "dn2", "dn3", "dn4", "dn5"); newDataNodes = Lists.newArrayList("dn6", "dn7", "dn8", "dn9"); SortedMap<String, List<MigrateTask>> tasks1 = MigrateUtils.balanceExpand(integerListMap, oldDataNodes, newDataNodes, totalSlots); Assert.assertEquals("{dn6=[MigrateTask{from='dn1'\n" + ", to='dn6'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=13, valueEnd=21)]\n" + "}, MigrateTask{from='dn2'\n" + ", to='dn6'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=46, valueEnd=48)]\n" + "}], dn7=[MigrateTask{from='dn2'\n" + ", to='dn7'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=49, valueEnd=54)]\n" + "}, MigrateTask{from='dn3'\n" + ", to='dn7'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=80, valueEnd=84)]\n" + "}], dn8=[MigrateTask{from='dn3'\n" + ", to='dn8'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=85, valueEnd=88)]\n" + "}, MigrateTask{from='dn4'\n" + ", to='dn8'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=0, valueEnd=6)]\n" + "}], dn9=[MigrateTask{from='dn4'\n" + ", to='dn9'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=7, valueEnd=8)]\n" + "}, MigrateTask{from='dn5'\n" + ", to='dn9'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=40, valueEnd=45), NodeIndexRange(nodeIndex=2, valueStart=66, valueEnd=68)]\n" + "}]}", Objects.toString(tasks1)); merge(integerListMap, tasks1); oldDataNodes = Lists.newArrayList("dn1", "dn2", "dn3", "dn4", "dn5", "dn6", "dn7", "dn8", "dn9"); newDataNodes = Lists.newArrayList("dn10", "dn11", "dn12", "dn13", "dn14", "dn15", "dn16", "dn17", "dn18", "dn19", "dn20", "dn21", "dn22", "dn23", "dn24", "dn25", "dn26", "dn27", "dn28", "dn29", "dn30", "dn31", "dn32", "dn33", "dn34", "dn35", "dn36", "dn37", "dn38", "dn39", "dn40", "dn41", "dn42", "dn43", "dn44", "dn45", "dn46", "dn47", "dn48", "dn49", "dn50", "dn51", "dn52", "dn53", "dn54", "dn55", "dn56", "dn57", "dn58", "dn59", "dn60", "dn61", "dn62", "dn63", "dn64", "dn65", "dn66", "dn67", "dn68", "dn69", "dn70", "dn71", "dn72", "dn73", "dn74", "dn75", "dn76", "dn77", "dn78", "dn79", "dn80", "dn81", "dn82", "dn83", "dn84", "dn85", "dn86", "dn87", "dn88", "dn89", "dn90", "dn91", "dn92", "dn93", "dn94", "dn95", "dn96", "dn97", "dn98", "dn99", "dn100"); SortedMap<String, List<MigrateTask>> tasks2 = MigrateUtils.balanceExpand(integerListMap, oldDataNodes, newDataNodes, totalSlots); Assert.assertEquals("{dn10=[MigrateTask{from='dn1'\n" + ", to='dn10'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=22, valueEnd=22)]\n" + "}], dn100=[MigrateTask{from='dn9'\n" + ", to='dn100'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=67, valueEnd=67)]\n" + "}], dn11=[MigrateTask{from='dn1'\n" + ", to='dn11'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=23, valueEnd=23)]\n" + "}], dn12=[MigrateTask{from='dn1'\n" + ", to='dn12'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=24, valueEnd=24)]\n" + "}], dn13=[MigrateTask{from='dn1'\n" + ", to='dn13'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=25, valueEnd=25)]\n" + "}], dn14=[MigrateTask{from='dn1'\n" + ", to='dn14'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=26, valueEnd=26)]\n" + "}], dn15=[MigrateTask{from='dn1'\n" + ", to='dn15'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=27, valueEnd=27)]\n" + "}], dn16=[MigrateTask{from='dn1'\n" + ", to='dn16'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=28, valueEnd=28)]\n" + "}], dn17=[MigrateTask{from='dn1'\n" + ", to='dn17'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=29, valueEnd=29)]\n" + "}], dn18=[MigrateTask{from='dn1'\n" + ", to='dn18'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=30, valueEnd=30)]\n" + "}], dn19=[MigrateTask{from='dn1'\n" + ", to='dn19'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=31, valueEnd=31)]\n" + "}], dn20=[MigrateTask{from='dn2'\n" + ", to='dn20'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=55, valueEnd=55)]\n" + "}], dn21=[MigrateTask{from='dn2'\n" + ", to='dn21'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=56, valueEnd=56)]\n" + "}], dn22=[MigrateTask{from='dn2'\n" + ", to='dn22'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=57, valueEnd=57)]\n" + "}], dn23=[MigrateTask{from='dn2'\n" + ", to='dn23'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=58, valueEnd=58)]\n" + "}], dn24=[MigrateTask{from='dn2'\n" + ", to='dn24'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=59, valueEnd=59)]\n" + "}], dn25=[MigrateTask{from='dn2'\n" + ", to='dn25'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=60, valueEnd=60)]\n" + "}], dn26=[MigrateTask{from='dn2'\n" + ", to='dn26'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=61, valueEnd=61)]\n" + "}], dn27=[MigrateTask{from='dn2'\n" + ", to='dn27'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=62, valueEnd=62)]\n" + "}], dn28=[MigrateTask{from='dn2'\n" + ", to='dn28'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=63, valueEnd=63)]\n" + "}], dn29=[MigrateTask{from='dn2'\n" + ", to='dn29'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=64, valueEnd=64)]\n" + "}], dn30=[MigrateTask{from='dn3'\n" + ", to='dn30'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=89, valueEnd=89)]\n" + "}], dn31=[MigrateTask{from='dn3'\n" + ", to='dn31'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=90, valueEnd=90)]\n" + "}], dn32=[MigrateTask{from='dn3'\n" + ", to='dn32'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=91, valueEnd=91)]\n" + "}], dn33=[MigrateTask{from='dn3'\n" + ", to='dn33'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=92, valueEnd=92)]\n" + "}], dn34=[MigrateTask{from='dn3'\n" + ", to='dn34'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=93, valueEnd=93)]\n" + "}], dn35=[MigrateTask{from='dn3'\n" + ", to='dn35'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=94, valueEnd=94)]\n" + "}], dn36=[MigrateTask{from='dn3'\n" + ", to='dn36'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=95, valueEnd=95)]\n" + "}], dn37=[MigrateTask{from='dn3'\n" + ", to='dn37'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=96, valueEnd=96)]\n" + "}], dn38=[MigrateTask{from='dn3'\n" + ", to='dn38'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=97, valueEnd=97)]\n" + "}], dn39=[MigrateTask{from='dn3'\n" + ", to='dn39'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=98, valueEnd=98)]\n" + "}], dn40=[MigrateTask{from='dn4'\n" + ", to='dn40'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=9, valueEnd=9)]\n" + "}], dn41=[MigrateTask{from='dn4'\n" + ", to='dn41'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=10, valueEnd=10)]\n" + "}], dn42=[MigrateTask{from='dn4'\n" + ", to='dn42'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=11, valueEnd=11)]\n" + "}], dn43=[MigrateTask{from='dn4'\n" + ", to='dn43'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=12, valueEnd=12)]\n" + "}], dn44=[MigrateTask{from='dn4'\n" + ", to='dn44'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=33, valueEnd=33)]\n" + "}], dn45=[MigrateTask{from='dn4'\n" + ", to='dn45'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=34, valueEnd=34)]\n" + "}], dn46=[MigrateTask{from='dn4'\n" + ", to='dn46'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=35, valueEnd=35)]\n" + "}], dn47=[MigrateTask{from='dn4'\n" + ", to='dn47'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=36, valueEnd=36)]\n" + "}], dn48=[MigrateTask{from='dn4'\n" + ", to='dn48'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=37, valueEnd=37)]\n" + "}], dn49=[MigrateTask{from='dn4'\n" + ", to='dn49'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=38, valueEnd=38)]\n" + "}], dn50=[MigrateTask{from='dn5'\n" + ", to='dn50'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=69, valueEnd=69)]\n" + "}], dn51=[MigrateTask{from='dn5'\n" + ", to='dn51'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=70, valueEnd=70)]\n" + "}], dn52=[MigrateTask{from='dn5'\n" + ", to='dn52'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=71, valueEnd=71)]\n" + "}], dn53=[MigrateTask{from='dn5'\n" + ", to='dn53'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=72, valueEnd=72)]\n" + "}], dn54=[MigrateTask{from='dn5'\n" + ", to='dn54'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=73, valueEnd=73)]\n" + "}], dn55=[MigrateTask{from='dn5'\n" + ", to='dn55'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=74, valueEnd=74)]\n" + "}], dn56=[MigrateTask{from='dn5'\n" + ", to='dn56'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=75, valueEnd=75)]\n" + "}], dn57=[MigrateTask{from='dn5'\n" + ", to='dn57'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=76, valueEnd=76)]\n" + "}], dn58=[MigrateTask{from='dn5'\n" + ", to='dn58'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=77, valueEnd=77)]\n" + "}], dn59=[MigrateTask{from='dn5'\n" + ", to='dn59'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=78, valueEnd=78)]\n" + "}], dn60=[MigrateTask{from='dn6'\n" + ", to='dn60'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=13, valueEnd=13)]\n" + "}], dn61=[MigrateTask{from='dn6'\n" + ", to='dn61'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=14, valueEnd=14)]\n" + "}], dn62=[MigrateTask{from='dn6'\n" + ", to='dn62'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=15, valueEnd=15)]\n" + "}], dn63=[MigrateTask{from='dn6'\n" + ", to='dn63'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=16, valueEnd=16)]\n" + "}], dn64=[MigrateTask{from='dn6'\n" + ", to='dn64'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=17, valueEnd=17)]\n" + "}], dn65=[MigrateTask{from='dn6'\n" + ", to='dn65'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=18, valueEnd=18)]\n" + "}], dn66=[MigrateTask{from='dn6'\n" + ", to='dn66'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=19, valueEnd=19)]\n" + "}], dn67=[MigrateTask{from='dn6'\n" + ", to='dn67'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=20, valueEnd=20)]\n" + "}], dn68=[MigrateTask{from='dn6'\n" + ", to='dn68'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=21, valueEnd=21)]\n" + "}], dn69=[MigrateTask{from='dn6'\n" + ", to='dn69'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=46, valueEnd=46)]\n" + "}], dn70=[MigrateTask{from='dn6'\n" + ", to='dn70'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=47, valueEnd=47)]\n" + "}], dn71=[MigrateTask{from='dn7'\n" + ", to='dn71'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=49, valueEnd=49)]\n" + "}], dn72=[MigrateTask{from='dn7'\n" + ", to='dn72'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=50, valueEnd=50)]\n" + "}], dn73=[MigrateTask{from='dn7'\n" + ", to='dn73'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=51, valueEnd=51)]\n" + "}], dn74=[MigrateTask{from='dn7'\n" + ", to='dn74'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=52, valueEnd=52)]\n" + "}], dn75=[MigrateTask{from='dn7'\n" + ", to='dn75'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=53, valueEnd=53)]\n" + "}], dn76=[MigrateTask{from='dn7'\n" + ", to='dn76'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=54, valueEnd=54)]\n" + "}], dn77=[MigrateTask{from='dn7'\n" + ", to='dn77'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=80, valueEnd=80)]\n" + "}], dn78=[MigrateTask{from='dn7'\n" + ", to='dn78'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=81, valueEnd=81)]\n" + "}], dn79=[MigrateTask{from='dn7'\n" + ", to='dn79'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=82, valueEnd=82)]\n" + "}], dn80=[MigrateTask{from='dn7'\n" + ", to='dn80'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=83, valueEnd=83)]\n" + "}], dn81=[MigrateTask{from='dn8'\n" + ", to='dn81'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=85, valueEnd=85)]\n" + "}], dn82=[MigrateTask{from='dn8'\n" + ", to='dn82'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=86, valueEnd=86)]\n" + "}], dn83=[MigrateTask{from='dn8'\n" + ", to='dn83'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=87, valueEnd=87)]\n" + "}], dn84=[MigrateTask{from='dn8'\n" + ", to='dn84'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=88, valueEnd=88)]\n" + "}], dn85=[MigrateTask{from='dn8'\n" + ", to='dn85'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=0, valueEnd=0)]\n" + "}], dn86=[MigrateTask{from='dn8'\n" + ", to='dn86'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=1, valueEnd=1)]\n" + "}], dn87=[MigrateTask{from='dn8'\n" + ", to='dn87'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=2, valueEnd=2)]\n" + "}], dn88=[MigrateTask{from='dn8'\n" + ", to='dn88'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=3, valueEnd=3)]\n" + "}], dn89=[MigrateTask{from='dn8'\n" + ", to='dn89'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=4, valueEnd=4)]\n" + "}], dn90=[MigrateTask{from='dn8'\n" + ", to='dn90'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=5, valueEnd=5)]\n" + "}], dn91=[MigrateTask{from='dn9'\n" + ", to='dn91'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=7, valueEnd=7)]\n" + "}], dn92=[MigrateTask{from='dn9'\n" + ", to='dn92'\n" + ", slots=[NodeIndexRange(nodeIndex=0, valueStart=8, valueEnd=8)]\n" + "}], dn93=[MigrateTask{from='dn9'\n" + ", to='dn93'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=40, valueEnd=40)]\n" + "}], dn94=[MigrateTask{from='dn9'\n" + ", to='dn94'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=41, valueEnd=41)]\n" + "}], dn95=[MigrateTask{from='dn9'\n" + ", to='dn95'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=42, valueEnd=42)]\n" + "}], dn96=[MigrateTask{from='dn9'\n" + ", to='dn96'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=43, valueEnd=43)]\n" + "}], dn97=[MigrateTask{from='dn9'\n" + ", to='dn97'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=44, valueEnd=44)]\n" + "}], dn98=[MigrateTask{from='dn9'\n" + ", to='dn98'\n" + ", slots=[NodeIndexRange(nodeIndex=1, valueStart=45, valueEnd=45)]\n" + "}], dn99=[MigrateTask{from='dn9'\n" + ", to='dn99'\n" + ", slots=[NodeIndexRange(nodeIndex=2, valueStart=66, valueEnd=66)]\n" + "}]}",tasks2.toString()); } | public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) { int newNodeSize = oldDataNodes.size() + newDataNodes.size(); int newSlotPerNode = slotsTotalNum / newNodeSize; TreeMap<String, List<MigrateTask>> newNodeTask = new TreeMap<>(); int remainder = slotsTotalNum - newSlotPerNode * (newNodeSize); for (int oldNodeIndex = 0; oldNodeIndex < integerListMap.size(); oldNodeIndex++) { List<NodeIndexRange> rangeList = integerListMap.get(oldNodeIndex); int needMoveNum = getCurTotalSize(rangeList) - newSlotPerNode; List<NodeIndexRange> allMoveList = getPartAndRemove(rangeList, needMoveNum); for (int newNodeIndex = 0; newNodeIndex < newDataNodes.size(); newNodeIndex++) { String newDataNode = newDataNodes.get(newNodeIndex); if (allMoveList.isEmpty()) { break; } List<MigrateTask> curRangeList = newNodeTask.computeIfAbsent(newDataNode, s -> new ArrayList<>()); int hasSlots = getCurTotalSizeForTask(curRangeList); int needMove = (newNodeIndex == 0) ? newSlotPerNode - hasSlots + remainder : newSlotPerNode - hasSlots; if (needMove > 0) { List<NodeIndexRange> moveList = getPartAndRemove(allMoveList, needMove); if (oldNodeIndex >= oldDataNodes.size()) { throw new IllegalArgumentException(); } curRangeList.add(new MigrateTask(oldDataNodes.get(oldNodeIndex), newDataNode, moveList)); newNodeTask.put(newDataNode, curRangeList); } } if (allMoveList.size() > 0) { throw new IllegalArgumentException("some slot has not moved to"); } } return newNodeTask; } | MigrateUtils { public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) { int newNodeSize = oldDataNodes.size() + newDataNodes.size(); int newSlotPerNode = slotsTotalNum / newNodeSize; TreeMap<String, List<MigrateTask>> newNodeTask = new TreeMap<>(); int remainder = slotsTotalNum - newSlotPerNode * (newNodeSize); for (int oldNodeIndex = 0; oldNodeIndex < integerListMap.size(); oldNodeIndex++) { List<NodeIndexRange> rangeList = integerListMap.get(oldNodeIndex); int needMoveNum = getCurTotalSize(rangeList) - newSlotPerNode; List<NodeIndexRange> allMoveList = getPartAndRemove(rangeList, needMoveNum); for (int newNodeIndex = 0; newNodeIndex < newDataNodes.size(); newNodeIndex++) { String newDataNode = newDataNodes.get(newNodeIndex); if (allMoveList.isEmpty()) { break; } List<MigrateTask> curRangeList = newNodeTask.computeIfAbsent(newDataNode, s -> new ArrayList<>()); int hasSlots = getCurTotalSizeForTask(curRangeList); int needMove = (newNodeIndex == 0) ? newSlotPerNode - hasSlots + remainder : newSlotPerNode - hasSlots; if (needMove > 0) { List<NodeIndexRange> moveList = getPartAndRemove(allMoveList, needMove); if (oldNodeIndex >= oldDataNodes.size()) { throw new IllegalArgumentException(); } curRangeList.add(new MigrateTask(oldDataNodes.get(oldNodeIndex), newDataNode, moveList)); newNodeTask.put(newDataNode, curRangeList); } } if (allMoveList.size() > 0) { throw new IllegalArgumentException("some slot has not moved to"); } } return newNodeTask; } } | MigrateUtils { public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) { int newNodeSize = oldDataNodes.size() + newDataNodes.size(); int newSlotPerNode = slotsTotalNum / newNodeSize; TreeMap<String, List<MigrateTask>> newNodeTask = new TreeMap<>(); int remainder = slotsTotalNum - newSlotPerNode * (newNodeSize); for (int oldNodeIndex = 0; oldNodeIndex < integerListMap.size(); oldNodeIndex++) { List<NodeIndexRange> rangeList = integerListMap.get(oldNodeIndex); int needMoveNum = getCurTotalSize(rangeList) - newSlotPerNode; List<NodeIndexRange> allMoveList = getPartAndRemove(rangeList, needMoveNum); for (int newNodeIndex = 0; newNodeIndex < newDataNodes.size(); newNodeIndex++) { String newDataNode = newDataNodes.get(newNodeIndex); if (allMoveList.isEmpty()) { break; } List<MigrateTask> curRangeList = newNodeTask.computeIfAbsent(newDataNode, s -> new ArrayList<>()); int hasSlots = getCurTotalSizeForTask(curRangeList); int needMove = (newNodeIndex == 0) ? newSlotPerNode - hasSlots + remainder : newSlotPerNode - hasSlots; if (needMove > 0) { List<NodeIndexRange> moveList = getPartAndRemove(allMoveList, needMove); if (oldNodeIndex >= oldDataNodes.size()) { throw new IllegalArgumentException(); } curRangeList.add(new MigrateTask(oldDataNodes.get(oldNodeIndex), newDataNode, moveList)); newNodeTask.put(newDataNode, curRangeList); } } if (allMoveList.size() > 0) { throw new IllegalArgumentException("some slot has not moved to"); } } return newNodeTask; } } | MigrateUtils { public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) { int newNodeSize = oldDataNodes.size() + newDataNodes.size(); int newSlotPerNode = slotsTotalNum / newNodeSize; TreeMap<String, List<MigrateTask>> newNodeTask = new TreeMap<>(); int remainder = slotsTotalNum - newSlotPerNode * (newNodeSize); for (int oldNodeIndex = 0; oldNodeIndex < integerListMap.size(); oldNodeIndex++) { List<NodeIndexRange> rangeList = integerListMap.get(oldNodeIndex); int needMoveNum = getCurTotalSize(rangeList) - newSlotPerNode; List<NodeIndexRange> allMoveList = getPartAndRemove(rangeList, needMoveNum); for (int newNodeIndex = 0; newNodeIndex < newDataNodes.size(); newNodeIndex++) { String newDataNode = newDataNodes.get(newNodeIndex); if (allMoveList.isEmpty()) { break; } List<MigrateTask> curRangeList = newNodeTask.computeIfAbsent(newDataNode, s -> new ArrayList<>()); int hasSlots = getCurTotalSizeForTask(curRangeList); int needMove = (newNodeIndex == 0) ? newSlotPerNode - hasSlots + remainder : newSlotPerNode - hasSlots; if (needMove > 0) { List<NodeIndexRange> moveList = getPartAndRemove(allMoveList, needMove); if (oldNodeIndex >= oldDataNodes.size()) { throw new IllegalArgumentException(); } curRangeList.add(new MigrateTask(oldDataNodes.get(oldNodeIndex), newDataNode, moveList)); newNodeTask.put(newDataNode, curRangeList); } } if (allMoveList.size() > 0) { throw new IllegalArgumentException("some slot has not moved to"); } } return newNodeTask; } static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum); static int getCurTotalSizeForTask(List<MigrateTask> rangeList); static int getCurTotalSize(List<NodeIndexRange> slots); static void merge(List<List<NodeIndexRange>> copy, SortedMap<String, List<MigrateTask>> tasks); static List<List<NodeIndexRange>> copy(List<List<NodeIndexRange>> integerListMap); } | MigrateUtils { public static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum) { int newNodeSize = oldDataNodes.size() + newDataNodes.size(); int newSlotPerNode = slotsTotalNum / newNodeSize; TreeMap<String, List<MigrateTask>> newNodeTask = new TreeMap<>(); int remainder = slotsTotalNum - newSlotPerNode * (newNodeSize); for (int oldNodeIndex = 0; oldNodeIndex < integerListMap.size(); oldNodeIndex++) { List<NodeIndexRange> rangeList = integerListMap.get(oldNodeIndex); int needMoveNum = getCurTotalSize(rangeList) - newSlotPerNode; List<NodeIndexRange> allMoveList = getPartAndRemove(rangeList, needMoveNum); for (int newNodeIndex = 0; newNodeIndex < newDataNodes.size(); newNodeIndex++) { String newDataNode = newDataNodes.get(newNodeIndex); if (allMoveList.isEmpty()) { break; } List<MigrateTask> curRangeList = newNodeTask.computeIfAbsent(newDataNode, s -> new ArrayList<>()); int hasSlots = getCurTotalSizeForTask(curRangeList); int needMove = (newNodeIndex == 0) ? newSlotPerNode - hasSlots + remainder : newSlotPerNode - hasSlots; if (needMove > 0) { List<NodeIndexRange> moveList = getPartAndRemove(allMoveList, needMove); if (oldNodeIndex >= oldDataNodes.size()) { throw new IllegalArgumentException(); } curRangeList.add(new MigrateTask(oldDataNodes.get(oldNodeIndex), newDataNode, moveList)); newNodeTask.put(newDataNode, curRangeList); } } if (allMoveList.size() > 0) { throw new IllegalArgumentException("some slot has not moved to"); } } return newNodeTask; } static SortedMap<String, List<MigrateTask>> balanceExpand(List<List<NodeIndexRange>> integerListMap, List<String> oldDataNodes, List<String> newDataNodes, int slotsTotalNum); static int getCurTotalSizeForTask(List<MigrateTask> rangeList); static int getCurTotalSize(List<NodeIndexRange> slots); static void merge(List<List<NodeIndexRange>> copy, SortedMap<String, List<MigrateTask>> tasks); static List<List<NodeIndexRange>> copy(List<List<NodeIndexRange>> integerListMap); } |
@Test public void init() { GPatternIdRecorder recorder = new GPatternIdRecorderImpl(false); recorder.load(Collections.emptySet()); GPatternUTF8Lexer utf8Lexer = new GPatternUTF8Lexer(recorder); String text = "1234 abc 1a2b3c 'a哈哈哈哈1' `qac`"; utf8Lexer.init(text); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("1234", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("abc", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("1a2b3c", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("'a哈哈哈哈1'", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("`qac`", utf8Lexer.getCurTokenString()); } | public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } | GPatternUTF8Lexer { public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } } | GPatternUTF8Lexer { public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } GPatternUTF8Lexer(GPatternIdRecorder idRecorder); } | GPatternUTF8Lexer { public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } GPatternUTF8Lexer(GPatternIdRecorder idRecorder); void init(String text); void init(ByteBuffer buffer, int startOffset, int limit); boolean nextToken(); boolean hasChar(); int peekAsciiChar(int step); int nextChar(); String getCurTokenString(); String getString(int start, int end); boolean fastEquals(int startOffset, int endOffset, byte[] symbol); } | GPatternUTF8Lexer { public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } GPatternUTF8Lexer(GPatternIdRecorder idRecorder); void init(String text); void init(ByteBuffer buffer, int startOffset, int limit); boolean nextToken(); boolean hasChar(); int peekAsciiChar(int step); int nextChar(); String getCurTokenString(); String getString(int start, int end); boolean fastEquals(int startOffset, int endOffset, byte[] symbol); static final int DEMO; static int ignorelength; } |
@Test public void testTimeout() throws Throwable { HttpLoader httpLoader = new HttpLoader(); final LoadedXml loadedXml = httpLoader.load("http: assertTrue(loadedXml.isEmpty()); } | public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); InputStream loadAsStream(final String url, final int timeout); LoadedXml load(final String url, final int timeout); } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); InputStream loadAsStream(final String url, final int timeout); LoadedXml load(final String url, final int timeout); } |
@Test public void testNonTimeout() throws Throwable { HttpLoader httpLoader = new HttpLoader(); final LoadedXml loadedXml = httpLoader.load("http: assertFalse(loadedXml.isEmpty()); } | public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); InputStream loadAsStream(final String url, final int timeout); LoadedXml load(final String url, final int timeout); } | HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); InputStream loadAsStream(final String url, final int timeout); LoadedXml load(final String url, final int timeout); } |
@Test public void testProcessFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/test.xml"); request.setNeedTransform(false); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_CONTENT, new String(baos.toByteArray()).trim()); } | public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); } |
@Test public void testTransformFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/test.xml"); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_TRANSFORMED_CONTENT.toLowerCase(), new String(baos.toByteArray()).trim().toLowerCase()); } | public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); } |
@Test public void testTransformXFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/xtest.xml"); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_CONTENT, new String(baos.toByteArray()).trim()); } | public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); } | YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); } |
@Test public void testAddUser() throws Exception { final long userId = createUser(); assertEquals(1, removeUser(userId)); } | public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } | DbUserService implements UserService { public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } } | DbUserService implements UserService { public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } } | DbUserService implements UserService { public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); } | DbUserService implements UserService { public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); } |
@Test public void testGetUser() throws Exception { final long userId = createUser(); final UserInfo userInfo = dbUserService.getUser(userId); assertEquals("xxx", userInfo.getLogin()); assertEquals("x x", userInfo.getFio()); assertEquals("123", userInfo.getPasswdHash()); assertEquals("11", userInfo.getPasswdAdd()); assertEquals(1, removeUser(userId)); } | public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } | DbUserService implements UserService { public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } } | DbUserService implements UserService { public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } } | DbUserService implements UserService { public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); } | DbUserService implements UserService { public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); } |
@Test public void testCheckUser() throws Exception { final long userId = createUser(); assertTrue(dbUserService.checkUser(userId, "123")); assertFalse(dbUserService.checkUser(userId * 2, "11")); assertFalse(dbUserService.checkUser(userId * 3, "123")); assertFalse(dbUserService.checkUser(userId, null)); assertFalse(dbUserService.checkUser(userId * 5, null)); assertEquals(1, removeUser(userId)); } | public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } | DbUserService implements UserService { public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } } | DbUserService implements UserService { public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } } | DbUserService implements UserService { public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); } | DbUserService implements UserService { public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); } |
@Test(expected = IllegalStateException.class) public void testInvalidSetup() { jm.setCacheDir(cacheDir); } | @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } | Minimizer implements IMinimizer { @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } } | Minimizer implements IMinimizer { @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } Minimizer(ResourceType type); @Inject Minimizer(ICompressor compressor, ResourceType type); } | Minimizer implements IMinimizer { @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } Minimizer(ResourceType type); @Inject Minimizer(ICompressor compressor, ResourceType type); @Override void enableDisableMinimize(boolean enable); @Override void enableDisableCompress(boolean enable); @Override void enableDisableCache(boolean enable); @Override void enableDisableInMemoryCache(boolean enable); @Override void enableDisableProcessInline(boolean enable); @Deprecated void enableDisableVerifyResource(boolean verify); @Override boolean isMinimizeEnabled(); @Override boolean isCompressEnabled(); @Override boolean isCacheEnabled(); @Override void setResourceDir(String dir); @Override void setRootDir(String dir); @Override void setUrlContextPath(String ctxPath); @Override void setCacheDir(File dir); @Override void setResourceUrlRoot(String urlRoot); @Override void setResourceUrlPath(String urlPath); @Override void setCacheUrlPath(String urlPath); @Override void clearCache(); @Override void setFileLocator(IFileLocator fileLocator); @Override void setBufferLocator(IBufferLocator bufferLocator); @Override void setRouteMapper(IRouteMapper routeMapper); @Override long getLastModified(File file); @Override void checkCache(); @Override List<String> process(List<String> resourceNames); @Override List<String> processWithoutMinimize(List<String> resourceNames); @Override String processInline(String content); @Override String processStatic(File file); IResource minimize(String resourceNames); static void copy_(Reader in, Writer out); ResourceType getType(); void setResourcesParam(String resourcesParam_); } | Minimizer implements IMinimizer { @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } Minimizer(ResourceType type); @Inject Minimizer(ICompressor compressor, ResourceType type); @Override void enableDisableMinimize(boolean enable); @Override void enableDisableCompress(boolean enable); @Override void enableDisableCache(boolean enable); @Override void enableDisableInMemoryCache(boolean enable); @Override void enableDisableProcessInline(boolean enable); @Deprecated void enableDisableVerifyResource(boolean verify); @Override boolean isMinimizeEnabled(); @Override boolean isCompressEnabled(); @Override boolean isCacheEnabled(); @Override void setResourceDir(String dir); @Override void setRootDir(String dir); @Override void setUrlContextPath(String ctxPath); @Override void setCacheDir(File dir); @Override void setResourceUrlRoot(String urlRoot); @Override void setResourceUrlPath(String urlPath); @Override void setCacheUrlPath(String urlPath); @Override void clearCache(); @Override void setFileLocator(IFileLocator fileLocator); @Override void setBufferLocator(IBufferLocator bufferLocator); @Override void setRouteMapper(IRouteMapper routeMapper); @Override long getLastModified(File file); @Override void checkCache(); @Override List<String> process(List<String> resourceNames); @Override List<String> processWithoutMinimize(List<String> resourceNames); @Override String processInline(String content); @Override String processStatic(File file); IResource minimize(String resourceNames); static void copy_(Reader in, Writer out); ResourceType getType(); void setResourcesParam(String resourcesParam_); static final String SYS_PROP_LESS_ENABLED; static final String SYS_PROP_COFFEE_ENABLED; } |
@Test public void shouldSendEmail() throws Exception { String to = "[email protected]"; String from = "[email protected]"; String title = "Title"; String content = "Content"; emailSender.sendEmail(to, from, title, content); MimeMessage[] receivedMessages = server.getReceivedMessages(); assertThat(receivedMessages.length).isEqualTo(1); MimeMessage receivedMessage = receivedMessages[0]; assertThat(receivedMessage.getAllRecipients()[0].toString()).isEqualTo(to); assertThat(receivedMessage.getFrom()[0].toString()).isEqualTo(from); assertThat(receivedMessage.getSubject()).isEqualTo(title); assertThat(receivedMessage.getContent().toString()).contains(content); assertThat(content).isEqualTo(GreenMailUtil.getBody(server.getReceivedMessages()[0])); } | void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } | EmailSender { void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } } | EmailSender { void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } EmailSender(JavaMailSender javaMailSender); } | EmailSender { void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } EmailSender(JavaMailSender javaMailSender); } | EmailSender { void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } EmailSender(JavaMailSender javaMailSender); } |
@Test public void unbindWhenDisposed() { Disposable disposable = MerlinFlowable.from(merlin) .subscribe(); disposable.dispose(); verify(merlin).unbind(); } | public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Flowable<NetworkStatus> from(Context context); static Flowable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Flowable<NetworkStatus> from(Merlin merlin); } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Flowable<NetworkStatus> from(Context context); static Flowable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Flowable<NetworkStatus> from(Merlin merlin); } |
@Test public void givenMissingDisconnectables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(connectables, null, bindables); registrar.clearRegistrations(); verifyZeroInteractions(disconnectables); } | 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 givenMissingBindables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(connectables, disconnectables, null); registrar.clearRegistrations(); verifyZeroInteractions(bindables); } | 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 givenSuccessfulRequest_whenSynchronouslyPinging_thenChecksResponseCodeIsValid() { given(responseCodeFetcher.from(ENDPOINT)).willReturn(RESPONSE_CODE); ping.doSynchronousPing(); verify(responseCodeValidator).isResponseCodeValid(RESPONSE_CODE); } | boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } |
@Test public void givenSuccessfulRequest_whenSynchronouslyPinging_thenReturnsTrue() { given(responseCodeFetcher.from(ENDPOINT)).willReturn(RESPONSE_CODE); given(responseCodeValidator.isResponseCodeValid(RESPONSE_CODE)).willReturn(true); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isTrue(); } | boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } |
@Test public void givenRequestFailsWithIOException_whenSynchronouslyPinging_thenReturnsFalse() { given(responseCodeFetcher.from(ENDPOINT)).willThrow(new RequestException(new IOException())); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isFalse(); } | boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } |
@Test public void givenRequestFailsWithRuntimeException_whenSynchronouslyPinging_thenReturnsFalse() { given(responseCodeFetcher.from(ENDPOINT)).willThrow(new RequestException(new RuntimeException())); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isFalse(); } | boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } | Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); } |
@Test public void whenBinding_thenBindsService() { merlin.bind(); verify(serviceBinder).bindService(); } | public void bind() { merlinServiceBinder.bindService(); } | Merlin { public void bind() { merlinServiceBinder.bindService(); } } | Merlin { public void bind() { merlinServiceBinder.bindService(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); } | Merlin { public void bind() { merlinServiceBinder.bindService(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } | Merlin { public void bind() { merlinServiceBinder.bindService(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } |
@Test public void whenUnbinding_thenUnbindsService() { merlin.unbind(); verify(serviceBinder).unbind(); } | public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } |
@Test public void whenUnbinding_thenClearsRegistrations() { merlin.unbind(); verify(registrar).clearRegistrations(); } | public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } | Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } |
@Test public void whenRegisteringConnectable_thenRegistersConnectable() { Connectable connectable = mock(Connectable.class); merlin.registerConnectable(connectable); verify(registrar).registerConnectable(connectable); } | public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } | Merlin { public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } } | Merlin { public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); } | Merlin { public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } | Merlin { public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } |
@Test public void notCrashWhenCreatingWithAMerlinBuilderWithoutCallbacks() { Context context = mock(Context.class); Merlin.Builder merlinBuilder = new Merlin.Builder(); MerlinFlowable.from(context, merlinBuilder).subscribe(); } | public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Flowable<NetworkStatus> from(Context context); static Flowable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Flowable<NetworkStatus> from(Merlin merlin); } | MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Flowable<NetworkStatus> from(Context context); static Flowable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Flowable<NetworkStatus> from(Merlin merlin); } |
@Test public void whenRegisteringDisconnectable_thenRegistersDisconnectable() { Disconnectable disconnectable = mock(Disconnectable.class); merlin.registerDisconnectable(disconnectable); verify(registrar).registerDisconnectable(disconnectable); } | public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } | Merlin { public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } } | Merlin { public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); } | Merlin { public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } | Merlin { public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } |
@Test public void whenRegisteringBindable_thenRegistersBindable() { Bindable bindable = mock(Bindable.class); merlin.registerBindable(bindable); verify(registrar).registerBindable(bindable); } | public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } | Merlin { public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } } | Merlin { public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); } | Merlin { public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } | Merlin { public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); } |
@Test public void givenNetworkInfo_whenExtracting_thenReturnsConnectivityChangeEvent() { given(connectivityManager.getNetworkInfo(ANY_NETWORK)).willReturn(networkInfo); ConnectivityChangeEvent connectivityChangeEvent = eventExtractor.extractFrom(ANY_NETWORK); assertThat(connectivityChangeEvent).isEqualTo(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_EXTRA_INFO, ANY_REASON )); } | ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); } |
@Test public void givenNetworkInfoIsUnavailable_whenExtracting_thenReturnsConnectivityChangeEventWithoutConnection() { given(connectivityManager.getNetworkInfo(ANY_NETWORK)).willReturn(UNAVAILABLE_NETWORK_INFO); ConnectivityChangeEvent connectivityChangeEvent = eventExtractor.extractFrom(ANY_NETWORK); assertThat(connectivityChangeEvent).isEqualTo(ConnectivityChangeEvent.createWithoutConnection()); } | ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); } | ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); } |
@Test public void whenPinging_thenCreatesPingTask() { endpointPinger.ping(pingerCallback); verify(pingTaskFactory).create(ENDPOINT, pingerCallback); } | void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } |
@Test public void whenPinging_thenExecutesPingTask() { endpointPinger.ping(pingerCallback); verify(pingTask).execute(); } | void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } | EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } |
@Test public void whenNoNetworkToPing_thenCallsOnFailure() { endpointPinger.noNetworkToPing(pingerCallback); verify(pingerCallback).onFailure(); } | void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } | EndpointPinger { void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } } | EndpointPinger { void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } | EndpointPinger { void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } | EndpointPinger { void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); } |
@Test public void givenNullIntent_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = null; notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } | void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } |
@Test public void givenIntentWithoutConnectivityAction_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithoutConnectivityAction(); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } | void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } |
@Test public void givenIntentWithConnectivityAction_whenNotifying_thenNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); notifier.notify(context, intent); verify(connectivityChangesNotifier).notify(ANY_CHANGE_EVENT); } | void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } |
@Test(expected = IllegalStateException.class) public void givenMissingRegister_whenRegisteringConnectable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Connectable connectable = mock(Connectable.class); registrar.registerConnectable(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 givenIntentWithConnectivityAction_butNullBinder_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); given(merlinBinderRetriever.retrieveConnectivityChangesNotifier(context)).willReturn(null); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } | void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } |
@Test public void givenIntentWithConnectivityAction_butIncorrectBinder_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); given(merlinBinderRetriever.retrieveConnectivityChangesNotifier(context)).willReturn(incorrectBinder()); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } | void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } |
@Test public void givenIntentWithConnectivityAction_butCannotNotify_whenNotifying_thenNeverNotifiesOfConnectivityChangeEvent() { Intent intent = givenIntentWithConnectivityAction(); given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); notifier.notify(context, intent); verify(connectivityChangesNotifier, never()).notify(any(ConnectivityChangeEvent.class)); } | void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } | ConnectivityReceiverConnectivityChangeNotifier { void notify(Context context, Intent intent) { if (intent != null && connectivityActionMatchesActionFor(intent)) { MerlinsBeard merlinsBeard = merlinsBeardCreator.createMerlinsBeard(context); ConnectivityChangeEvent connectivityChangeEvent = creator.createFrom(intent, merlinsBeard); notifyMerlinService(context, connectivityChangeEvent); } } ConnectivityReceiverConnectivityChangeNotifier(ConnectivityReceiver.MerlinsBeardCreator merlinsBeardCreator,
ConnectivityReceiver.MerlinBinderRetriever merlinBinderRetriever,
ConnectivityChangeEventCreator creator); } |
@Test public void givenRegisteredBroadcastReceiver_whenBindingForASecondTime_thenOriginalBroadcastReceiverIsRegisteredAgain() { ArgumentCaptor<ConnectivityReceiver> broadcastReceiver = givenRegisteredBroadcastReceiver(); connectivityChangesRegister.register(connectivityChangesNotifier); verify(context, times(2)).registerReceiver(eq(broadcastReceiver.getValue()), refEq(new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))); } | void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } |
@Test public void givenRegisteredBroadcastReceiver_whenUnbinding_thenUnregistersOriginallyRegisteredBroadcastReceiver() { ArgumentCaptor<ConnectivityReceiver> broadcastReceiver = givenRegisteredBroadcastReceiver(); connectivityChangesRegister.unregister(); verify(context).unregisterReceiver(broadcastReceiver.getValue()); } | void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenRegisteredMerlinNetworkCallbacks_whenBindingForASecondTime_thenOriginalNetworkCallbacksIsRegisteredAgain() { ArgumentCaptor<ConnectivityCallbacks> merlinNetworkCallback = givenRegisteredMerlinNetworkCallbacks(); connectivityChangesRegister.register(connectivityChangesNotifier); verify(connectivityManager, times(2)).registerNetworkCallback(refEq((new NetworkRequest.Builder()).build()), eq(merlinNetworkCallback.getValue())); } | void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenRegisteredMerlinNetworkCallback_whenUnbinding_thenUnregistersOriginallyRegisteredNetworkCallbacks() { ArgumentCaptor<ConnectivityCallbacks> merlinNetworkCallback = givenRegisteredMerlinNetworkCallbacks(); connectivityChangesRegister.unregister(); verify(connectivityManager).unregisterNetworkCallback(merlinNetworkCallback.getValue()); } | void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } | ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); } |
@Test public void givenRegisteredConnectable_whenCallingOnConnect_thenCallsConnectForConnectable() { Bindable bindable = givenRegisteredBindable(); bindCallbackManager.onMerlinBind(networkStatus); verify(bindable).onBind(networkStatus); } | void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); } |
@Test public void givenMultipleRegisteredConnectables_whenCallingOnConnect_thenCallsConnectForAllConnectables() { List<Bindable> bindables = givenMultipleRegisteredBindables(); bindCallbackManager.onMerlinBind(networkStatus); for (Bindable bindable : bindables) { verify(bindable).onBind(networkStatus); } } | void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); } | BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); } |
@Test public void givenNetworkWasConnected_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { givenNetworkWas(CONNECTED); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager).onMerlinBind(AVAILABLE_NETWORK); } | void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } |
@Test(expected = IllegalStateException.class) public void givenMissingRegister_thenRegisteringDisconnectable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Disconnectable disconnectable = mock(Disconnectable.class); registrar.registerDisconnectable(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 givenNetworkWasDisconnected_whenNotifyingOfInitialState_thenForwardsNetworkUnavailableToListener() { givenNetworkWas(DISCONNECTED); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager).onMerlinBind(NetworkStatus.newUnavailableInstance()); } | void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } |
@Test public void givenEndpointPingHasNotOccurred_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { given(networkStatusRetriever.retrieveNetworkStatus()).willReturn(AVAILABLE_NETWORK); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager).onMerlinBind(AVAILABLE_NETWORK); } | void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } |
@Test public void givenConnectivityChangeEvent_whenNotifyingOfConnectivityChangeEvent_thenDelegatesRefreshingToRetriever() { ConnectivityChangeEvent connectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(CONNECTED, ANY_INFO, ANY_REASON); connectivityChangesForwarder.forward(connectivityChangeEvent); verify(networkStatusRetriever).fetchWithPing(eq(endpointPinger), any(EndpointPinger.PingerCallback.class)); } | void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } | ConnectivityChangesForwarder { void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } } | ConnectivityChangesForwarder { void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } |
@Test public void givenNetworkWasConnected_andNullBindListener_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { connectivityChangesForwarder = new ConnectivityChangesForwarder( networkStatusRetriever, disconnectCallbackManager, connectCallbackManager, null, endpointPinger ); givenNetworkWas(CONNECTED); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager, never()).onMerlinBind(any(NetworkStatus.class)); } | void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } |
@Test public void givenEndpointPingHasNotOccurred_andNullBindListener_whenNotifyingOfInitialState_thenForwardsNetworkAvailableToListener() { connectivityChangesForwarder = new ConnectivityChangesForwarder( networkStatusRetriever, disconnectCallbackManager, connectCallbackManager, null, endpointPinger ); given(networkStatusRetriever.retrieveNetworkStatus()).willReturn(AVAILABLE_NETWORK); connectivityChangesForwarder.forwardInitialNetworkStatus(); verify(bindCallbackManager, never()).onMerlinBind(any(NetworkStatus.class)); } | void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } | ConnectivityChangesForwarder { void forwardInitialNetworkStatus() { if (bindCallbackManager == null) { return; } if (hasPerformedEndpointPing()) { bindCallbackManager.onMerlinBind(lastEndpointPingNetworkStatus); return; } bindCallbackManager.onMerlinBind(networkStatusRetriever.retrieveNetworkStatus()); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); } |
@Test public void whenReceivingAnIntent_thenForwardsToConnectivityChangeNotifier() { connectivityReceiver.onReceive(context, intent); verify(notifier).notify(context, intent); } | @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } | ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } } | ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } ConnectivityReceiver(); ConnectivityReceiver(ConnectivityReceiverConnectivityChangeNotifier connectivityReceiverConnectivityChangeNotifier); } | ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } ConnectivityReceiver(); ConnectivityReceiver(ConnectivityReceiverConnectivityChangeNotifier connectivityReceiverConnectivityChangeNotifier); @Override void onReceive(Context context, Intent intent); } | ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } ConnectivityReceiver(); ConnectivityReceiver(ConnectivityReceiverConnectivityChangeNotifier connectivityReceiverConnectivityChangeNotifier); @Override void onReceive(Context context, Intent intent); } |
@Test public void givenMerlinsBeardIsConnected_whenFetchingWithPing_thenPingsUsingHostPinger() { given(merlinsBeards.isConnected()).willReturn(CONNECTED); networkStatusRetriever.fetchWithPing(endpointPinger, pingerCallback); verify(endpointPinger).ping(pingerCallback); } | void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); } |
@Test public void givenMerlinsBeardIsDisconnected_whenFetchingWithPing_thenCallsNoNetworkToPing() { given(merlinsBeards.isConnected()).willReturn(DISCONNECTED); networkStatusRetriever.fetchWithPing(endpointPinger, pingerCallback); verify(endpointPinger).noNetworkToPing(pingerCallback); } | void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); } | NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); } |