Search in sources :

Example 6 with EventHubConfigurationDto

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

the class KeyManagerConfigurationDataRetriever method run.

@Override
public void run() {
    APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    if (apiManagerConfiguration != null) {
        EventHubConfigurationDto eventHubConfigurationDto = apiManagerConfiguration.getEventHubConfigurationDto();
        if (eventHubConfigurationDto != null && eventHubConfigurationDto.isEnabled()) {
            try {
                String url = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP).concat("/keymanagers");
                byte[] credentials = Base64.encodeBase64((eventHubConfigurationDto.getUsername() + ":" + eventHubConfigurationDto.getPassword()).getBytes());
                HttpGet method = new HttpGet(url);
                method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
                method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
                URL configUrl = new URL(url);
                int port = configUrl.getPort();
                String protocol = configUrl.getProtocol();
                HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
                HttpResponse httpResponse = null;
                int retryCount = 0;
                boolean retry;
                do {
                    try {
                        httpResponse = httpClient.execute(method);
                        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                            String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                            KeyManagerConfiguration[] keyManagerConfigurations = new Gson().fromJson(responseString, KeyManagerConfiguration[].class);
                            for (KeyManagerConfiguration keyManagerConfiguration : keyManagerConfigurations) {
                                if (keyManagerConfiguration.isEnabled()) {
                                    try {
                                        ServiceReferenceHolder.getInstance().getKeyManagerConfigurationService().addKeyManagerConfiguration(keyManagerConfiguration.getTenantDomain(), keyManagerConfiguration.getName(), keyManagerConfiguration.getType(), keyManagerConfiguration);
                                    } catch (APIManagementException e) {
                                        log.error("Error while configuring Key Manager " + keyManagerConfiguration.getName() + " in tenant " + keyManagerConfiguration.getTenantDomain(), e);
                                    }
                                }
                            }
                            retry = false;
                        } else {
                            retry = true;
                            retryCount++;
                        }
                    } catch (IOException ex) {
                        retryCount++;
                        int maxRetries = 15;
                        if (retryCount < maxRetries) {
                            retry = true;
                            long retryTimeout = (long) Math.min(Math.pow(2, retryCount), 300);
                            log.warn("Failed retrieving Key Manager Configurations from remote " + "endpoint: " + ex.getMessage() + ". Retrying after " + retryTimeout + " seconds...");
                            Thread.sleep(retryTimeout * 1000);
                        } else {
                            throw ex;
                        }
                    }
                } while (retry);
            } catch (InterruptedException | IOException e) {
                log.error("Error while retrieving key manager configurations", e);
            }
        }
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) URL(java.net.URL) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)

Example 7 with EventHubConfigurationDto

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

the class BlockingConditionRetrieverTest method run.

@Test
public void run() throws Exception {
    String content = "{\"api\":[\"/pizzashack/1.0.0\"],\"application\":[\"admin:DefaultApplication\"]," + "\"ip\":[{\"fixedIp\":\"127.0.0.1\",\"invert\":false,\"type\":\"IP\",\"tenantDomain\":\"carbon" + ".super\"}],\"user\":[\"admin\"],\"custom\":[]}";
    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);
    StatusLine status = Mockito.mock(StatusLine.class);
    Mockito.when(status.getStatusCode()).thenReturn(200);
    Mockito.when(httpResponse.getStatusLine()).thenReturn(status);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
    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:18083/internal/data/v1");
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    BlockingConditionRetriever blockingConditionRetriever = new BlockingConditionRetrieverWrapper(eventHubConfigurationDto, throttleDataHolder);
    blockingConditionRetriever.run();
    Assert.assertTrue(throttleDataHolder.isRequestBlocked("/pizzashack/1.0.0", "admin:DefaultApplication", "admin", "127.0.0.1", "carbon.super", "/pizzashack/1.0.0:1.0.0:admin-DefaultApplication"));
}
Also used : StatusLine(org.apache.http.StatusLine) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 8 with EventHubConfigurationDto

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

the class APIManagerConfiguration method setEventHubConfiguration.

private void setEventHubConfiguration(OMElement omElement) {
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    OMElement enableElement = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.ENABLE));
    if (enableElement != null && Boolean.parseBoolean(enableElement.getText())) {
        eventHubConfigurationDto.setEnabled(true);
        OMElement serviceUrlElement = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.SERVICE_URL));
        if (serviceUrlElement != null) {
            String serviceUrl = APIUtil.replaceSystemProperty(serviceUrlElement.getText());
            if (StringUtils.isNotEmpty(serviceUrl)) {
                serviceUrl = serviceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0];
                eventHubConfigurationDto.setServiceUrl(serviceUrl);
            }
        }
        OMElement initDelay = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.INIT_DELAY));
        if (initDelay != null) {
            eventHubConfigurationDto.setInitDelay(Integer.parseInt(initDelay.getText()));
        }
        OMElement usernameElement = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.USERNAME));
        if (usernameElement != null) {
            eventHubConfigurationDto.setUsername(usernameElement.getText());
        }
        OMElement passwordElement = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.PASSWORD));
        if (passwordElement != null) {
            String password = MiscellaneousUtil.resolve(passwordElement, secretResolver);
            eventHubConfigurationDto.setPassword(APIUtil.replaceSystemProperty(password).toCharArray());
        }
        OMElement configurationRetrieverElement = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.EVENT_RECEIVER_CONFIGURATION));
        if (configurationRetrieverElement != null) {
            EventHubConfigurationDto.EventHubReceiverConfiguration eventHubReceiverConfiguration = new EventHubConfigurationDto.EventHubReceiverConfiguration();
            Iterator receiverConnectionDetailsElements = configurationRetrieverElement.getChildElements();
            Properties properties = new Properties();
            while (receiverConnectionDetailsElements.hasNext()) {
                OMElement element = (OMElement) receiverConnectionDetailsElements.next();
                String value = MiscellaneousUtil.resolve(element, secretResolver);
                properties.put(element.getLocalName(), APIUtil.replaceSystemProperty(value));
            }
            eventHubReceiverConfiguration.setJmsConnectionParameters(properties);
            eventHubConfigurationDto.setEventHubReceiverConfiguration(eventHubReceiverConfiguration);
        }
        OMElement eventPublisherElement = omElement.getFirstChildWithName(new QName(APIConstants.KeyManager.EVENT_PUBLISHER_CONFIGURATIONS));
        EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = new EventHubConfigurationDto.EventHubPublisherConfiguration();
        if (eventPublisherElement != null) {
            OMElement receiverUrlGroupElement = eventPublisherElement.getFirstChildWithName(new QName(APIConstants.AdvancedThrottleConstants.DATA_PUBLISHER_CONFIGURAION_REVEIVER_URL_GROUP));
            if (receiverUrlGroupElement != null) {
                eventHubPublisherConfiguration.setReceiverUrlGroup(APIUtil.replaceSystemProperty(receiverUrlGroupElement.getText()));
            }
            OMElement authUrlGroupElement = eventPublisherElement.getFirstChildWithName(new QName(APIConstants.AdvancedThrottleConstants.DATA_PUBLISHER_CONFIGURAION_AUTH_URL_GROUP));
            if (authUrlGroupElement != null) {
                eventHubPublisherConfiguration.setAuthUrlGroup(APIUtil.replaceSystemProperty(authUrlGroupElement.getText()));
            }
            OMElement eventTypeElement = eventPublisherElement.getFirstChildWithName(new QName(APIConstants.AdvancedThrottleConstants.DATA_PUBLISHER_CONFIGURAION_TYPE));
            if (eventTypeElement != null) {
                eventHubPublisherConfiguration.setType(eventTypeElement.getText().trim());
            }
            Map<String, String> publisherProps = extractPublisherProperties(eventPublisherElement);
            if (publisherProps != null) {
                eventHubPublisherConfiguration.setProperties(publisherProps);
            }
            eventHubConfigurationDto.setEventHubPublisherConfiguration(eventHubPublisherConfiguration);
        }
    }
    this.eventHubConfigurationDto = eventHubConfigurationDto;
}
Also used : EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) QName(javax.xml.namespace.QName) Iterator(java.util.Iterator) OMElement(org.apache.axiom.om.OMElement) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)

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