com.netflix.discovery.shared.Application Java Examples

The following examples show how to use com.netflix.discovery.shared.Application. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiCatalogControllerTests.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void whenGetAllContainers_givenNothing_thenReturnContainersWithState() {
    Application service1 = new Application("service-1");
    service1.addInstance(getStandardInstance("service1", InstanceInfo.InstanceStatus.UP));

    Application service2 = new Application("service-2");
    service1.addInstance(getStandardInstance("service2", InstanceInfo.InstanceStatus.DOWN));

    given(this.cachedServicesService.getService("service1")).willReturn(service1);
    given(this.cachedServicesService.getService("service2")).willReturn(service2);
    given(this.cachedProductFamilyService.getAllContainers()).willReturn(createContainers());

    RestAssuredMockMvc.standaloneSetup(apiCatalogController);
    RestAssuredMockMvc.given().
        when().
        get("/containers").
        then().
        statusCode(200);
}
 
Example #2
Source File: InstanceLookupExecutorTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 2000)
public void testRun_whenInstanceExistInDiscovery() throws InterruptedException {
    when(eurekaClient.getApplication(SERVICE_ID))
        .thenReturn(new Application(SERVICE_ID, instances));

    instanceLookupExecutor.run(
        SERVICE_ID,
        instanceInfo -> {
            lastInstanceInfo = instanceInfo;
            latch.countDown();
        }, null
    );

    latch.await();

    assertNull(lastException);
    assertNotNull(lastInstanceInfo);
    assertEquals(instances.get(0), lastInstanceInfo);
}
 
Example #3
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void noZosmfInstance() {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication();
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(ServiceNotAccessibleException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not ServiceNotAccessibleException");
    assertEquals("z/OSMF instance not found or incorrectly configured.", exception.getMessage());
}
 
Example #4
Source File: InstanceRegistry.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: InstanceRefreshService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get this instance service details and check if it should be processed
 *
 * @param containersUpdated  containers, which were updated
 * @param cachedServices     existing services
 * @param deltaFromDiscovery changed service instances
 * @param instance           this instance
 */
private void processServiceInstance(Set<String> containersUpdated, Applications cachedServices,
                                    Applications deltaFromDiscovery, InstanceInfo instance) {
    Application application = null;
    // Get the application which this instance belongs to
    if (cachedServices != null && cachedServices.getRegisteredApplications() != null) {
        application = cachedServices.getRegisteredApplications().stream()
            .filter(service -> service.getName().equalsIgnoreCase(instance.getAppName())).findFirst().orElse(null);
    }
    // if its new then it will only be in the delta
    if (application == null || application.getInstances().isEmpty()) {
        application = deltaFromDiscovery.getRegisteredApplications().stream()
            .filter(service -> service.getName().equalsIgnoreCase(instance.getAppName())).findFirst().orElse(null);
    }

    // there's no chance which this case is not called. It's just double check
    if (application == null || application.getInstances().isEmpty()) {
        log.debug("Instance {} couldn't get details from cache and delta", instance.getAppName());
        return;
    }

    processInstance(containersUpdated, instance, application);
}
 
Example #6
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void notValidZosmfResponse() {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, COOKIE1);
    headers.add(HttpHeaders.SET_COOKIE, COOKIE2);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(new ZosmfServiceFacade.ZosmfInfo(), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(AuthenticationServiceException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not AuthenticationServiceException");
    assertEquals("z/OSMF domain cannot be read.", exception.getMessage());
}
 
Example #7
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void noDomainInResponse() throws IOException {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, COOKIE1);
    headers.add(HttpHeaders.SET_COOKIE, COOKIE2);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(getResponse(false), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(AuthenticationServiceException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not AuthenticationServiceException");
    assertEquals("z/OSMF domain cannot be read.", exception.getMessage());
}
 
Example #8
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void invalidCookieInResponse() throws IOException {
    String invalidCookie = "LtpaToken=test";

    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, invalidCookie);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(getResponse(true), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(BadCredentialsException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not BadCredentialsException");
    assertEquals("Username or password are invalid.", exception.getMessage());
}
 
Example #9
Source File: ApiCatalogControllerTests.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void whenGetSingleContainer_thenPopulateApiDocForServicesExceptOneWhichFails() throws ContainerStatusRetrievalException {
    Application service1 = new Application("service-1");
    service1.addInstance(getStandardInstance("service1", InstanceInfo.InstanceStatus.UP));

    Application service2 = new Application("service-2");
    service1.addInstance(getStandardInstance("service2", InstanceInfo.InstanceStatus.DOWN));

    given(this.cachedServicesService.getService("service1")).willReturn(service1);
    given(this.cachedServicesService.getService("service2")).willReturn(service2);
    given(this.cachedProductFamilyService.getContainerById("api-one")).willReturn(createContainers().get(0));
    given(this.cachedApiDocService.getApiDocForService("service1", "v1")).willReturn("service1");
    given(this.cachedApiDocService.getApiDocForService("service2", "v1")).willThrow(new RuntimeException());
    ResponseEntity<List<APIContainer>> containers = this.apiCatalogController.getAPIContainerById("api-one");
    Assert.assertNotNull(containers.getBody());
    Assert.assertEquals(1, containers.getBody().size());
    containers.getBody().forEach(apiContainer ->
        apiContainer.getServices().forEach(apiService -> {
            if (apiService.getServiceId().equals("service1")) {
                Assert.assertEquals(apiService.getServiceId(), apiService.getApiDoc());
            }
            if (apiService.getServiceId().equals("service2")) {
                Assert.assertNull(apiService.getApiDoc());
            }
        }));
}
 
Example #10
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void cookieWithSemicolon() throws IOException {
    String cookie = "LtpaToken2=test;";

    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, cookie);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(getResponse(true), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Authentication tokenAuthentication = zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication);

    assertTrue(tokenAuthentication.isAuthenticated());
    assertEquals(USERNAME, tokenAuthentication.getPrincipal());
}
 
Example #11
Source File: DriverServiceImpl.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Boolean> driverStatus(DriverDto driverDto) {
    Map<String, Boolean> driverStatusMap = new HashMap<>(16);

    Page<Driver> driverPage = list(driverDto);
    if (driverPage.getRecords().size() > 0) {
        List<String> services = new ArrayList<>();
        List<Application> applications = eurekaClient.getApplications().getRegisteredApplications();
        applications.forEach(application -> services.add(application.getName().toLowerCase()));

        driverPage.getRecords().forEach(driver -> {
            boolean status = false;
            if (services.contains(driver.getServiceName())) {
                status = true;
            }
            driverStatusMap.put(driver.getServiceName(), status);
        });
    }
    return driverStatusMap;
}
 
Example #12
Source File: InstanceRegistry.java    From didi-eureka-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #13
Source File: InstanceLookupExecutorTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 2000)
public void testRun_whenNoInstancesExistInDiscovery() throws InterruptedException {
    when(eurekaClient.getApplication(SERVICE_ID))
        .thenReturn(new Application(SERVICE_ID, Collections.emptyList()));

    instanceLookupExecutor.run(
        SERVICE_ID, null,
        (exception, isStopped) -> {
            lastException = exception;
            latch.countDown();
        }
    );

    latch.await();

    assertNotNull(lastException);
    assertTrue(lastException instanceof InstanceNotFoundException);
    assertEquals("'" + SERVICE_ID + "' has no running instances registered to Discovery Service",
        lastException.getMessage());
}
 
Example #14
Source File: InstanceRetrievalServiceTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGetAllInstancesFromDiscovery_whenNeedApplicationsWithoutFilter() throws JsonProcessingException {
    Map<String, InstanceInfo> instanceInfoMap = createInstances();


    Applications expectedApplications = new Applications();
    instanceInfoMap.forEach((key, value) -> expectedApplications.addApplication(new Application(value.getAppName(), Collections.singletonList(value))));

    ObjectMapper mapper = new ObjectMapper();
    String bodyAll = mapper.writeValueAsString(new ApplicationsWrapper(expectedApplications));
    mockRetrieveApplicationService(discoveryServiceAllAppsUrl, bodyAll);

    Applications actualApplications = instanceRetrievalService.getAllInstancesFromDiscovery(false);

    assertEquals(expectedApplications.size(), actualApplications.size());

    List<Application> actualApplicationList =
        new ArrayList<>(actualApplications.getRegisteredApplications());


    expectedApplications
        .getRegisteredApplications()
        .forEach(expectedApplication ->
            assertThat(actualApplicationList, hasItem(hasProperty("name", equalTo(expectedApplication.getName()))))
        );
}
 
Example #15
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void loginWithExistingUser() throws IOException {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, COOKIE1);
    headers.add(HttpHeaders.SET_COOKIE, COOKIE2);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(getResponse(true), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Authentication tokenAuthentication
        = zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication);

    assertTrue(tokenAuthentication.isAuthenticated());
    assertEquals(USERNAME, tokenAuthentication.getPrincipal());
}
 
Example #16
Source File: GatewayNotifierTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testServiceUpdated() {
    verify(restTemplate, never()).delete(anyString());

    List<InstanceInfo> instances = Arrays.asList(
        createInstanceInfo("hostname1", 1000, 1433),
        createInstanceInfo("hostname2", 1000, 0)
    );

    Application application = mock(Application.class);
    when(application.getInstances()).thenReturn(instances);
    when(registry.getApplication("GATEWAY")).thenReturn(application);

    gatewayNotifierSync.serviceUpdated("testService", null);
    verify(restTemplate, times(1)).delete("https://hostname1:1433/gateway/cache/services/testService");
    verify(restTemplate, times(1)).delete("http://hostname2:1000/gateway/cache/services/testService");

    gatewayNotifierSync.serviceUpdated(null, null);
    verify(restTemplate, times(1)).delete("https://hostname1:1433/gateway/cache/services");
    verify(restTemplate, times(1)).delete("http://hostname2:1000/gateway/cache/services");

    verify(restTemplate, times(4)).delete(anyString());
}
 
Example #17
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void loginWithBadUser() throws IOException {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(getResponse(true), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(BadCredentialsException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not BadCredentialsException");
    assertEquals("Username or password are invalid.", exception.getMessage());
}
 
Example #18
Source File: EurekaRegisterHandler.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<EndpointF> query(String name) {
    name = normalObjName(name);
    if (name == null) {
        return null;
    }
    Application application = client.getApplication(name);
    List<EndpointF> results = new ArrayList<EndpointF>();
    if (application == null) {
        return results;
    }
    for (InstanceInfo instanceInfo : application.getInstances()) {
        if (instanceInfo.getStatus() != InstanceStatus.UP) {
            continue;
        }
        EndpointF endpoint = convert2Endpoint(instanceInfo);
        if (endpoint != null) {
            results.add(endpoint);
        }
    }
    return results;
}
 
Example #19
Source File: InstanceRetrievalServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetAllInstancesFromDiscovery_whenNeedApplicationsWithDeltaFilter() throws JsonProcessingException {
    String discoveryServiceAppsUrl = discoveryConfigProperties.getLocations() + APPS_ENDPOINT + DELTA_ENDPOINT;

    Map<String, InstanceInfo> instanceInfoMap = createInstances();

    Applications expectedApplications = new Applications();
    instanceInfoMap.forEach((key, value) -> expectedApplications.addApplication(new Application(value.getAppName(), Collections.singletonList(value))));

    ObjectMapper mapper = new ObjectMapper();
    String bodyAll = mapper.writeValueAsString(new ApplicationsWrapper(expectedApplications));
    mockRetrieveApplicationService(discoveryServiceAppsUrl, bodyAll);

    Applications actualApplications = instanceRetrievalService.getAllInstancesFromDiscovery(true);

    assertEquals(expectedApplications.size(), actualApplications.size());

    List<Application> actualApplicationList =
        new ArrayList<>(actualApplications.getRegisteredApplications());


    expectedApplications
        .getRegisteredApplications()
        .forEach(expectedApplication ->
            assertThat(actualApplicationList, hasItem(hasProperty("name", equalTo(expectedApplication.getName()))))
        );
}
 
Example #20
Source File: InstanceRefreshServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testServiceAddedToDiscoveryThatIsNotInCache() {
    ContainerServiceState cachedState = containerServiceMockUtil.createContainersServicesAndInstances();
    containerServiceMockUtil.mockServiceRetrievalFromCache(cachedServicesService, cachedState.getApplications());

    ContainerServiceState discoveredState = new ContainerServiceState();
    discoveredState.setServices(new ArrayList<>());
    discoveredState.setContainers(new ArrayList<>());
    discoveredState.setInstances(new ArrayList<>());
    discoveredState.setApplications(new ArrayList<>());

    // start up a new instance of service 5 and add it to the service1 application
    HashMap<String, String> metadata = new HashMap<>();
    metadata.put(CATALOG_ID, "api-five");
    InstanceInfo newInstanceOfService5
        = containerServiceMockUtil.createInstance("service5", "service5:9999", InstanceInfo.InstanceStatus.UP,
        InstanceInfo.ActionType.ADDED, metadata);
    discoveredState.getInstances().add(newInstanceOfService5);
    Application service5 = new Application("service5", Collections.singletonList(newInstanceOfService5));
    discoveredState.getApplications().add(service5);

    // Mock the discovery and cached service query
    Applications discoveredServices = new Applications("1", 1L, discoveredState.getApplications());
    when(instanceRetrievalService.getAllInstancesFromDiscovery(true)).thenReturn(discoveredServices);

    Applications cachedServices = new Applications("1", 1L, cachedState.getApplications());
    when(cachedServicesService.getAllCachedServices()).thenReturn(cachedServices);

    when(cachedProductFamilyService.saveContainerFromInstance("api-five", newInstanceOfService5))
        .thenReturn(new APIContainer());

    instanceRefreshService.refreshCacheFromDiscovery();

    verify(cachedProductFamilyService, times(1))
        .saveContainerFromInstance("api-five", newInstanceOfService5);
}
 
Example #21
Source File: InstanceRefreshServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefreshCacheFromDiscovery_whenGatewayClientIsNotInitialized() {
    when(gatewayClient.isInitialized()).thenReturn(false);

    instanceRefreshService.refreshCacheFromDiscovery();

    verify(cachedServicesService, never())
        .updateService(anyString(), any(Application.class));
}
 
Example #22
Source File: InstanceRefreshServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefreshCacheFromDiscovery_whenApiCatalogIsNotInCache() {
    when(cachedServicesService.getService(CoreService.API_CATALOG.getServiceId())).thenReturn(null);

    instanceRefreshService.refreshCacheFromDiscovery();

    verify(cachedServicesService, never())
        .updateService(anyString(), any(Application.class));
}
 
Example #23
Source File: ZosmfServiceV2Test.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private void mockZosmfService(String hostname, int port) {
    InstanceInfo instanceInfo = mock(InstanceInfo.class);
    when(instanceInfo.getHostName()).thenReturn(hostname);
    when(instanceInfo.getPort()).thenReturn(port);
    Application application = mock(Application.class);
    when(application.getInstances()).thenReturn(Collections.singletonList(instanceInfo));
    when(discovery.getApplication(ZOSMF_ID)).thenReturn(application);
}
 
Example #24
Source File: GatewayNotifierTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDistributeInvalidatedCredentials() {
    InstanceInfo targetInstanceInfo = createInstanceInfo("host", 1000, 1433);
    String targetInstanceId = targetInstanceInfo.getInstanceId();

    InstanceInfo gatewayInstance = createInstanceInfo("gateway", 111, 123);
    String gatewayUrl = "https://gateway:123/gateway/auth/distribute/" + targetInstanceId;

    Application application = mock(Application.class);
    when(application.getInstances()).thenReturn(Collections.singletonList(gatewayInstance));
    when(registry.getApplication("GATEWAY")).thenReturn(application);

    final String messageNotifyError = "org.zowe.apiml.discovery.errorNotifyingGateway";
    when(messageService.createMessage(messageNotifyError)).thenReturn(createMessage(messageNotifyError));
    final String messageKey = "org.zowe.apiml.discovery.registration.gateway.notify";
    Message msg = createMessage(messageKey, gatewayUrl, targetInstanceId);
    when(messageService.createMessage(messageKey, gatewayUrl, targetInstanceId)).thenReturn(msg);

    // succeed notified
    gatewayNotifierSync.distributeInvalidatedCredentials(targetInstanceId);
    verify(restTemplate, times(1)).getForEntity(eq(gatewayUrl), any(), (Exception) any());

    // error on notification
    when(restTemplate.getForEntity(anyString(), any())).thenThrow(new RuntimeException());
    gatewayNotifierSync.distributeInvalidatedCredentials(targetInstanceId);
    verify(messageService, times(1)).createMessage(messageKey, gatewayUrl, targetInstanceId);
}
 
Example #25
Source File: GatewayNotifierTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNotificationFailed() {
    MessageTemplate messageTemplate = new MessageTemplate("key", "number", MessageType.ERROR, "text");
    Message message = Message.of("requestedKey", messageTemplate, new Object[0]);
    when(messageService.createMessage(anyString(), (Object[]) any())).thenReturn(message);
    doThrow(new RuntimeException("any exception")).when(restTemplate).delete(anyString());
    List<InstanceInfo> instances = new LinkedList<>();
    Application application = mock(Application.class);
    when(application.getInstances()).thenReturn(instances);
    when(registry.getApplication("GATEWAY")).thenReturn(application);

    // no gateway is registred
    gatewayNotifierSync.serviceUpdated("service", "host:service:1433");
    verify(restTemplate, never()).delete(anyString());

    // notify gateway itself
    instances.add(createInstanceInfo("GATEWAY","host", 1000, 1433));
    gatewayNotifierSync.serviceUpdated("GATEWAY", "host:GATEWAY:1433");
    verify(restTemplate, never()).delete(anyString());

    // notify gateway and restTemplate failed
    gatewayNotifierSync.serviceUpdated("service", "host2:service:123");
    verify(restTemplate, times(1)).delete(anyString());
    verify(messageService).createMessage(
        "org.zowe.apiml.discovery.registration.gateway.notify",
        "https://host:1433/gateway/cache/services/service",
        "host2:service:123"
    );
}
 
Example #26
Source File: GatewayNotifier.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private List<InstanceInfo> getGatewayInstances() {
    final PeerAwareInstanceRegistry registry = getRegistry();
    final Application application = registry.getApplication(GATEWAY_SERVICE_ID);
    if (application == null) {
        logger.log("org.zowe.apiml.discovery.errorNotifyingGateway");
        return Collections.emptyList();
    }
    return application.getInstances();
}
 
Example #27
Source File: InstanceRegistryTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenew() throws Exception {
	// Creating two instances of the app
	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);
	// creating application list with an app having two instances
	final Application application = new Application(APP_NAME,
			Arrays.asList(instanceInfo1, instanceInfo2));
	final List<Application> applications = new ArrayList<>();
	applications.add(application);
	// stubbing applications list
	doReturn(applications).when(instanceRegistry).getSortedApplications();
	// calling tested method
	instanceRegistry.renew(APP_NAME, INSTANCE_ID, false);
	instanceRegistry.renew(APP_NAME, "my-host-name:8009", false);
	// event of proper type is registered
	assertThat(this.testEvents.applicationEvents.size()).isEqualTo(2);
	assertThat(this.testEvents.applicationEvents
			.get(0) instanceof EurekaInstanceRenewedEvent).isTrue();
	assertThat(this.testEvents.applicationEvents
			.get(1) instanceof EurekaInstanceRenewedEvent).isTrue();
	// event details are correct
	final EurekaInstanceRenewedEvent event1 = (EurekaInstanceRenewedEvent) (this.testEvents.applicationEvents
			.get(0));
	assertThat(event1.getAppName()).isEqualTo(APP_NAME);
	assertThat(event1.getServerId()).isEqualTo(INSTANCE_ID);
	assertThat(event1.getSource()).isEqualTo(instanceRegistry);
	assertThat(event1.getInstanceInfo()).isEqualTo(instanceInfo1);
	assertThat(event1.isReplication()).isFalse();

	final EurekaInstanceRenewedEvent event2 = (EurekaInstanceRenewedEvent) (this.testEvents.applicationEvents
			.get(1));
	assertThat(event2.getInstanceInfo()).isEqualTo(instanceInfo2);
}
 
Example #28
Source File: EurekaApplicationsTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
void givenEurekaClient_whenRetrieveRegisteredApps_thenReturnApps() {
    EurekaApplications retrieval = new EurekaApplications(eurekaClient);
    Applications applications = mock(Applications.class);
    List<Application> applicationList = new ArrayList<>();
    applicationList.add(mock(Application.class));

    Mockito.when(eurekaClient.getApplications()).thenReturn(applications);
    Mockito.when(eurekaClient.getApplications().getRegisteredApplications()).thenReturn(applicationList);

    List<Application> registeredApps = retrieval.getRegistered();

    assertFalse(registeredApps.isEmpty());
}
 
Example #29
Source File: ZosmfServiceV1Test.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private void mockZosmfService(String hostname, int port) {
    InstanceInfo instanceInfo = mock(InstanceInfo.class);
    when(instanceInfo.getHostName()).thenReturn(hostname);
    when(instanceInfo.getPort()).thenReturn(port);
    Application application = mock(Application.class);
    when(application.getInstances()).thenReturn(Collections.singletonList(instanceInfo));
    when(discovery.getApplication(ZOSMF_ID)).thenReturn(application);
}
 
Example #30
Source File: InstanceInfoMeta.java    From onetwo with Apache License 2.0 5 votes vote down vote up
static public Optional<InstanceInfo> findInstanceInfoById(String instId) {
	List<Application> sortedApplications = getEurekaServerContext().getRegistry().getSortedApplications();
	Optional<InstanceInfo> inst = sortedApplications.stream().filter(app -> {
		return app.getByInstanceId(instId)!=null;
	})
	.findFirst()
	.map(app -> app.getByInstanceId(instId));
	return inst;
}