Search in sources :

Example 1 with EventHubConfigurationDto

use of org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto in project carbon-apimgt by wso2.

the class APILoggerManager method invokeService.

private String invokeService(String path, String tenantDomain) throws IOException, APIManagementException {
    String serviceURLStr = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP);
    HttpGet method = new HttpGet(serviceURLStr + path);
    URL serviceURL = new URL(serviceURLStr + path);
    byte[] credentials = getServiceCredentials(eventHubConfigurationDto);
    int servicePort = serviceURL.getPort();
    String serviceProtocol = serviceURL.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(servicePort, serviceProtocol);
    HttpResponse httpResponse = null;
    int retryCount = 0;
    boolean retry;
    do {
        try {
            httpResponse = httpClient.execute(method);
            retry = false;
        } catch (IOException ex) {
            retryCount++;
            if (retryCount < RETRIEVAL_RETRIES) {
                retry = true;
                log.warn("Failed retrieving " + path + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + RETRIEVAL_TIMEOUT_IN_SECONDS + " seconds.");
                try {
                    Thread.sleep(RETRIEVAL_TIMEOUT_IN_SECONDS * 1000L);
                } catch (InterruptedException e) {
                // Ignore
                }
            } else {
                throw new APIManagementException("Error while calling internal service", ex);
            }
        }
    } while (retry);
    if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
        log.error("Could not retrieve subscriptions for tenantDomain : " + tenantDomain);
        throw new APIManagementException("Error while retrieving subscription from " + path);
    }
    return EntityUtils.toString(httpResponse.getEntity(), UTF8);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 2 with EventHubConfigurationDto

use of org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto in project carbon-apimgt by wso2.

the class APIManagerComponent method configureNotificationEventPublisher.

/**
 * Method to configure wso2event type event adapter to be used for event notification.
 */
private void configureNotificationEventPublisher() throws APIManagementException {
    Map<String, String> properties = new HashMap<>();
    if (ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() != null) {
        APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        if (configuration.getEventHubConfigurationDto().getEventHubPublisherConfiguration() != null && configuration.getEventHubConfigurationDto().isEnabled()) {
            EventHubConfigurationDto eventHubConfigurationDto = configuration.getEventHubConfigurationDto();
            EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = eventHubConfigurationDto.getEventHubPublisherConfiguration();
            properties.put(APIConstants.RECEIVER_URL, eventHubPublisherConfiguration.getReceiverUrlGroup());
            properties.put(APIConstants.AUTHENTICATOR_URL, eventHubPublisherConfiguration.getAuthUrlGroup());
            properties.put(APIConstants.USERNAME, eventHubConfigurationDto.getUsername());
            properties.put(APIConstants.PASSWORD, eventHubConfigurationDto.getPassword());
            properties.put(APIConstants.PROTOCOL, eventHubPublisherConfiguration.getType());
            properties.put(APIConstants.PUBLISHING_MODE, APIConstants.NON_BLOCKING);
            properties.put(APIConstants.PUBLISHING_TIME_OUT, "0");
            for (String key : eventHubPublisherConfiguration.getProperties().keySet()) {
                properties.put(key, eventHubPublisherConfiguration.getProperties().get(key));
            }
            properties.put(APIConstants.IS_ENABLED, Boolean.toString(configuration.getEventHubConfigurationDto().isEnabled()));
            try {
                ServiceReferenceHolder.getInstance().getEventPublisherFactory().configure(properties);
            } catch (EventPublisherException e) {
                throw new APIManagementException(e);
            }
        } else {
            log.info("Wso2Event Publisher not enabled.");
        }
    } else {
        log.info("api-manager.xml not loaded. Wso2Event Publisher will not be enabled.");
    }
}
Also used : EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException)

Example 3 with EventHubConfigurationDto

use of org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto in project carbon-apimgt by wso2.

the class KeyMgtNotificationSender method notify.

public void notify(KeyManagerConfigurationDTO keyManagerConfigurationDTO, String action) {
    String encodedString = "";
    if (keyManagerConfigurationDTO.getAdditionalProperties() != null) {
        String additionalProperties = new Gson().toJson(keyManagerConfigurationDTO.getAdditionalProperties());
        encodedString = new String(Base64.encodeBase64(additionalProperties.getBytes()));
    }
    Object[] objects = new Object[] { APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_CONFIGURATION, action, keyManagerConfigurationDTO.getName(), keyManagerConfigurationDTO.getType(), keyManagerConfigurationDTO.isEnabled(), encodedString, keyManagerConfigurationDTO.getOrganization(), keyManagerConfigurationDTO.getTokenType() };
    Event keyManagerEvent = new Event(APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_STREAM_ID, System.currentTimeMillis(), null, null, objects);
    EventHubConfigurationDto eventHubConfigurationDto = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getEventHubConfigurationDto();
    if (eventHubConfigurationDto.isEnabled()) {
        EventPublisherEvent notificationEvent = new EventPublisherEvent(APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_STREAM_ID, System.currentTimeMillis(), objects, keyManagerEvent.toString());
        APIUtil.publishEvent(EventPublisherType.KEYMGT_EVENT, notificationEvent, keyManagerEvent.toString());
    }
}
Also used : EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) EventPublisherEvent(org.wso2.carbon.apimgt.eventing.EventPublisherEvent) Gson(com.google.gson.Gson) Event(org.wso2.carbon.databridge.commons.Event) EventPublisherEvent(org.wso2.carbon.apimgt.eventing.EventPublisherEvent)

Example 4 with EventHubConfigurationDto

use of org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto in project carbon-apimgt by wso2.

the class KeyTemplateRetrieverTest method run.

@Test
public void run() throws Exception {
    Map map = new HashMap();
    map.put("$userId", "$userId");
    map.put("$apiContext", "$apiContext");
    map.put("$apiVersion", "$apiVersion");
    String content = "[\"$userId\",\"$apiContext\",\"$apiVersion\"]";
    PowerMockito.mockStatic(APIUtil.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream(content.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
    StatusLine status = Mockito.mock(StatusLine.class);
    Mockito.when(status.getStatusCode()).thenReturn(200);
    Mockito.when(httpResponse.getStatusLine()).thenReturn(status);
    BDDMockito.given(APIUtil.getHttpClient(Mockito.anyInt(), Mockito.anyString())).willReturn(httpClient);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setUsername("admin");
    eventHubConfigurationDto.setPassword("admin".toCharArray());
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setServiceUrl("http://localhost:18084/internal/data/v1");
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    KeyTemplateRetriever keyTemplateRetriever = new KeyTemplateRetrieverWrapper(eventHubConfigurationDto, throttleDataHolder);
    keyTemplateRetriever.run();
    Map<String, String> keyTemplateMap = throttleDataHolder.getKeyTemplateMap();
    Assert.assertNotNull(keyTemplateMap);
    Assert.assertEquals(map, keyTemplateMap);
}
Also used : ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) StatusLine(org.apache.http.StatusLine) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.http.client.HttpClient) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 5 with EventHubConfigurationDto

use of org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto in project carbon-apimgt by wso2.

the class APIManagerComponentTest method testShouldActivateWhenAllPrerequisitesMet.

@Test
public void testShouldActivateWhenAllPrerequisitesMet() throws Exception {
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(AuthorizationUtils.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(SQLConstantManagerFactory.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    ComponentContext componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService configurationService = Mockito.mock(APIManagerConfigurationService.class);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    Registry registry = Mockito.mock(Registry.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    OutputEventAdapterService adapterService = Mockito.mock(OutputEventAdapterService.class);
    ThrottleProperties throttleProperties = new ThrottleProperties();
    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.doNothing().when(authManager).authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Mockito.doNothing().when(adapterService).create(null);
    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("").thenReturn(null);
    Mockito.when(bundleContext.registerService("", CommonConfigDeployer.class, null)).thenReturn(null);
    Mockito.when(authManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(configurationService);
    Mockito.when(serviceReferenceHolder.getOutputEventAdapterService()).thenReturn(adapterService);
    Mockito.when(configurationService.getAPIManagerConfiguration()).thenReturn(configuration);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(configuration.getThrottleProperties()).thenReturn(throttleProperties);
    PowerMockito.doNothing().when(APIMgtDBUtil.class, "initialize");
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantExternalStoreConfig", Mockito.anyString());
    PowerMockito.doNothing().when(AuthorizationUtils.class, "addAuthorizeRoleListener", Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    PowerMockito.doNothing().when(SQLConstantManagerFactory.class, "initializeSQLConstantManager");
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    APIManagerComponent apiManagerComponent = new APIManagerComponentWrapper(registry);
    GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
    Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setInitDelay(0);
    eventHubConfigurationDto.setUsername("a");
    eventHubConfigurationDto.setPassword("sss".toCharArray());
    eventHubConfigurationDto.setServiceUrl("https://localhost");
    EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = new EventHubConfigurationDto.EventHubPublisherConfiguration();
    eventHubConfigurationDto.setEventHubPublisherConfiguration(eventHubPublisherConfiguration);
    Mockito.when(config.getEventHubConfigurationDto()).thenReturn(eventHubConfigurationDto);
    try {
        apiManagerComponent.activate(componentContext);
    } catch (FileNotFoundException f) {
        // Exception thrown here means that method was continued without the configuration file
        Assert.fail("Should not throw an exception");
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) ComponentContext(org.osgi.service.component.ComponentContext) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) FileNotFoundException(java.io.FileNotFoundException) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) Registry(org.wso2.carbon.registry.api.Registry) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) OutputEventAdapterService(org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService) APIManagerComponentWrapper(org.wso2.carbon.apimgt.impl.internal.util.APIManagerComponentWrapper) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) BundleContext(org.osgi.framework.BundleContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

EventHubConfigurationDto (org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto)7 HttpResponse (org.apache.http.HttpResponse)4 HttpClient (org.apache.http.client.HttpClient)4 HttpGet (org.apache.http.client.methods.HttpGet)4 Test (org.junit.Test)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)3 Gson (com.google.gson.Gson)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 StatusLine (org.apache.http.StatusLine)2 BasicHttpEntity (org.apache.http.entity.BasicHttpEntity)2 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)2 GatewayArtifactSynchronizerProperties (org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties)2 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)2 FileNotFoundException (java.io.FileNotFoundException)1 Iterator (java.util.Iterator)1