Java Code Examples for org.wso2.carbon.apimgt.impl.utils.APIUtil#getHttpClient()
The following examples show how to use
org.wso2.carbon.apimgt.impl.utils.APIUtil#getHttpClient() .
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: GatewayUtils.java From carbon-apimgt with Apache License 2.0 | 6 votes |
public static String retrieveJWKSConfiguration(String jwksEndpoint) throws IOException { URL url = new URL(jwksEndpoint); try (CloseableHttpClient httpClient = (CloseableHttpClient) APIUtil .getHttpClient(url.getPort(), url.getProtocol())) { HttpGet httpGet = new HttpGet(jwksEndpoint); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); try (InputStream content = entity.getContent()) { return IOUtils.toString(content); } } else { return null; } } } }
Example 2
Source File: APISynchronizer.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Method to deploy * * @param api * @param apiId * @param seqId * @param accessTokenDTO * @param uri * @throws APISynchronizationException */ private void deploySequenceFromUrl(APIDTO api, String apiId, String seqId, AccessTokenDTO accessTokenDTO, String uri, String username) throws APISynchronizationException { try { String apiPublisherUrl = ConfigManager.getConfigurationDTO().getUrl_publisher(); if (apiPublisherUrl == null) { apiPublisherUrl = OnPremiseGatewayConstants.DEFAULT_API_PUBLISHER_URL; if (log.isDebugEnabled()) { log.debug("Using default API publisher URL: " + apiPublisherUrl); } } URL apiPublisherUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiPublisherUrl); HttpClient httpClient = APIUtil.getHttpClient(apiPublisherUrlValue.getPort(), apiPublisherUrlValue .getProtocol()); HttpGet httpGet = new HttpGet(uri); String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken(); httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue); // Retrieve all API specific mediation policies from publisher REST API String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet, OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT); if (log.isDebugEnabled()) { log.debug("Received response from GET api sequence: " + seqId); } InputStream is = new ByteArrayInputStream(response.getBytes( Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET))); ObjectMapper mapper = new ObjectMapper(); MediationDTO mediationDTO = mapper.readValue(is, MediationDTO.class); writeSequenceToFile(mediationDTO, api, username); } catch (OnPremiseGatewayException | IOException | APIManagementException e) { throw new APISynchronizationException("An error occurred while deploying custom sequences of API " + apiId, e); } }
Example 3
Source File: ThrottlingSynchronizer.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private SubscriptionThrottlePolicyListDTO getSubscriptionPolicies(AccessTokenDTO accessTokenDTO) throws OnPremiseGatewayException, IOException { if (log.isDebugEnabled()) { log.debug("Getting Subscription Policies using Admin REST API."); } String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin(); if (apiAdminUrl == null) { apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL; if (log.isDebugEnabled()) { log.debug("Using default API Admin URL." + apiAdminUrl); } } URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl); HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol()); HttpGet httpGet = new HttpGet(subscriptionPolicyUrl); String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken(); httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue); String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet, OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT); if (log.isDebugEnabled()) { log.debug("Received response from GET Subscription Policies : " + response); } InputStream is = new ByteArrayInputStream(response.getBytes( Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET))); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, SubscriptionThrottlePolicyListDTO.class); }
Example 4
Source File: ThrottlingSynchronizer.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private ApplicationThrottlePolicyListDTO getApplicationPolicies(AccessTokenDTO accessTokenDTO) throws OnPremiseGatewayException, IOException { if (log.isDebugEnabled()) { log.debug("Getting Subscription Policies using Admin REST API."); } String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin(); if (apiAdminUrl == null) { apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL; if (log.isDebugEnabled()) { log.debug("Using default API Admin URL." + apiAdminUrl); } } URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl); HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol()); HttpGet httpGet = new HttpGet(applicationPolicyUrl); String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken(); httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue); String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet, OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT); if (log.isDebugEnabled()) { log.debug("Received response from GET Application Policies : " + response); } InputStream is = new ByteArrayInputStream(response.getBytes( Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET))); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, ApplicationThrottlePolicyListDTO.class); }
Example 5
Source File: ThrottlingSynchronizer.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private AdvancedThrottlePolicyListDTO getAdvancedPolicies(AccessTokenDTO accessTokenDTO) throws OnPremiseGatewayException, IOException { if (log.isDebugEnabled()) { log.debug("Getting Advanced Policies using Admin REST API."); } String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin(); if (apiAdminUrl == null) { apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL; if (log.isDebugEnabled()) { log.debug("Using default API Admin URL." + apiAdminUrl); } } URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl); HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol()); HttpGet httpGet = new HttpGet(advancedPolicyUrl); String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken(); httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue); String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet, OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT); if (log.isDebugEnabled()) { log.debug("Received response from GET Advanced Policies : " + response); } InputStream is = new ByteArrayInputStream(response.getBytes( Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET))); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, AdvancedThrottlePolicyListDTO.class); }
Example 6
Source File: ThrottlingSynchronizer.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private List<AdvancedThrottlePolicyDTO> getAdvancedPolicyList(AccessTokenDTO accessTokenDTO, AdvancedThrottlePolicyListDTO policyListDTO) throws OnPremiseGatewayException { List<AdvancedThrottlePolicyDTO> policyDTOList = new ArrayList<>(); String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin(); if (apiAdminUrl == null) { apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL; if (log.isDebugEnabled()) { log.debug("Using default API Admin URL." + apiAdminUrl); } } URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl); HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol()); for (AdvancedThrottlePolicyInfoDTO infoDTO : policyListDTO.getList()) { HttpGet httpGet = new HttpGet(advancedPolicyUrl + ThrottlingConstants.URL_PATH_SEPARATOR + infoDTO.getPolicyId()); String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken(); httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue); String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet, OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT); if (log.isDebugEnabled()) { log.debug("Received response from GET Advanced Policy : " + response); } InputStream is = new ByteArrayInputStream(response.getBytes( Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET))); ObjectMapper mapper = new ObjectMapper(); try { policyDTOList.add(mapper.readValue(is, AdvancedThrottlePolicyDTO.class)); } catch (IOException e) { throw new OnPremiseGatewayException("Error occurred while getting Advanced Policies.", e); } } return policyDTOList; }
Example 7
Source File: ThrottlingSynchronizer.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private BlockingConditionListDTO getBlockingConditions(AccessTokenDTO accessTokenDTO) throws OnPremiseGatewayException, IOException { if (log.isDebugEnabled()) { log.debug("Getting Blocking conditions using Admin REST API."); } String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin(); if (apiAdminUrl == null) { apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL; if (log.isDebugEnabled()) { log.debug("Using default API Admin URL." + apiAdminUrl); } } URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl); HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol()); HttpGet httpGet = new HttpGet(blockingPolicyUrl); String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken(); httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue); String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet, OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT); if (log.isDebugEnabled()) { log.debug("Received response from GET Blocking Conditions : " + response); } InputStream is = new ByteArrayInputStream(response.getBytes( Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET))); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, BlockingConditionListDTO.class); }
Example 8
Source File: WSO2APIPublisher.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Get HTTP Client for service endpoint port and protocol. * * @param storeEndpoint service endpoint URL Eg: http://localhost:9763/api/am/admin/v0.16/import/api * Eg: http://localhost:9763/api/am/publisher/v0.16 * @return HTTP Client * @throws APIManagementException If an error occurs due to malformed URL. */ protected CloseableHttpClient getHttpClient(String storeEndpoint) throws APIManagementException { try { URL storeURL = new URL(storeEndpoint); int externalStorePort = storeURL.getPort(); String externalStoreProtocol = storeURL.getProtocol(); return (CloseableHttpClient) APIUtil.getHttpClient(externalStorePort, externalStoreProtocol); } catch (MalformedURLException e) { throw new APIManagementException("Error while initializing HttpClient due to malformed URL", e); } }
Example 9
Source File: OASParserUtil.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * This method validates the given OpenAPI definition by URL * * @param url URL of the API definition * @param returnJsonContent whether to return the converted json form of the * @return APIDefinitionValidationResponse object with validation information */ public static APIDefinitionValidationResponse validateAPIDefinitionByURL(String url, boolean returnJsonContent) throws APIManagementException { APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse(); try { URL urlObj = new URL(url); HttpClient httpClient = APIUtil.getHttpClient(urlObj.getPort(), urlObj.getProtocol()); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8"); validationResponse = validateAPIDefinition(responseStr, returnJsonContent); } else { validationResponse.setValid(false); validationResponse.getErrorItems().add(ExceptionCodes.OPENAPI_URL_NO_200); } } catch (IOException e) { ErrorHandler errorHandler = ExceptionCodes.OPENAPI_URL_MALFORMED; //Log the error and continue since this method is only intended to validate a definition log.error(errorHandler.getErrorDescription(), e); validationResponse.setValid(false); validationResponse.getErrorItems().add(errorHandler); } return validationResponse; }
Example 10
Source File: RevokedJWTTokensRetriever.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method will retrieve revoked JWT tokens by calling a web service. * * @return List of RevokedJWTTokensDTOs. */ private RevokedJWTTokenDTO[] retrieveRevokedJWTTokensData() { try { // The resource resides in the throttle web app. Hence reading throttle configs String url = getEventHubConfiguration().getServiceUrl() + "/revokedjwt"; HttpGet method = new HttpGet(url); byte[] credentials = Base64.encodeBase64((getEventHubConfiguration().getUsername() + ":" + getEventHubConfiguration().getPassword()).getBytes(StandardCharsets.UTF_8)); method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8)); URL keyMgtURL = new URL(url); int keyMgtPort = keyMgtURL.getPort(); String keyMgtProtocol = keyMgtURL.getProtocol(); HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol); HttpResponse httpResponse = null; int retryCount = 0; boolean retry; do { try { httpResponse = httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < revokedJWTTokensRetrievalRetries) { retry = true; log.warn("Failed retrieving revoked JWT token signatures from remote endpoint: " + ex.getMessage() + ". Retrying after " + revokedJWTTokensRetrievalTimeoutInSeconds + " seconds..."); Thread.sleep(revokedJWTTokensRetrievalTimeoutInSeconds * 1000); } else { throw ex; } } } while (retry); String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); if (responseString != null && !responseString.isEmpty()) { return new Gson().fromJson(responseString, RevokedJWTTokenDTO[].class); } } catch (IOException | InterruptedException e) { log.error("Exception when retrieving revoked JWT tokens from remote endpoint ", e); } return null; }
Example 11
Source File: BlockingConditionRetriever.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method will retrieve blocking conditions by calling a WebService. * * @return String object array which contains throttled keys. */ private BlockConditionsDTO retrieveBlockConditionsData() { try { String url = getEventHubConfiguration().getServiceUrl() + "/block"; byte[] credentials = Base64.encodeBase64((getEventHubConfiguration().getUsername() + ":" + getEventHubConfiguration().getPassword()).getBytes (StandardCharsets.UTF_8)); HttpGet method = new HttpGet(url); method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8)); URL eventHubUrl = new URL(url); int keyMgtPort = eventHubUrl.getPort(); String protocol = eventHubUrl.getProtocol(); HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, protocol); HttpResponse httpResponse = null; int retryCount = 0; boolean retry; do { try { httpResponse = httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < blockConditionsDataRetrievalRetries) { retry = true; log.warn("Failed retrieving Blocking Conditions from remote endpoint: " + ex.getMessage() + ". Retrying after " + blockConditionsDataRetrievalTimeoutInSeconds + " seconds..."); Thread.sleep(blockConditionsDataRetrievalTimeoutInSeconds * 1000); } else { throw ex; } } } while(retry); String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); if (responseString != null && !responseString.isEmpty()) { return new Gson().fromJson(responseString, BlockConditionsDTO.class); } } catch (IOException | InterruptedException e) { log.error("Exception when retrieving Blocking Conditions from remote endpoint ", e); } return null; }
Example 12
Source File: KeyTemplateRetriever.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method will retrieve KeyTemplates * * @return String object array which contains Blocking conditions. */ private String[] retrieveKeyTemplateData() { try { String url = getEventHubConfiguration().getServiceUrl() + "/keyTemplates"; byte[] credentials = Base64.encodeBase64( (getEventHubConfiguration().getUsername() + ":" + getEventHubConfiguration().getPassword()) .getBytes(StandardCharsets.UTF_8)); HttpGet method = new HttpGet(url); method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8)); URL keyMgtURL = new URL(url); int keyMgtPort = keyMgtURL.getPort(); String keyMgtProtocol = keyMgtURL.getProtocol(); HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol); HttpResponse httpResponse = null; int retryCount = 0; boolean retry; do { try { httpResponse = httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < keyTemplateRetrievalRetries) { retry = true; log.warn("Failed retrieving throttling data from remote endpoint: " + ex.getMessage() + ". Retrying after " + keyTemplateRetrievalTimeoutInSeconds + " seconds..."); Thread.sleep(keyTemplateRetrievalTimeoutInSeconds * 1000); } else { throw ex; } } } while(retry); String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); if (responseString != null && !responseString.isEmpty()) { JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseString); return (String[]) jsonArray.toArray(new String[jsonArray.size()]); } } catch (IOException | InterruptedException | ParseException e) { log.error("Exception when retrieving throttling data from remote endpoint ", e); } return null; }
Example 13
Source File: KeyMgtRegistrationService.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method will be used to register a service provider application in the authorization server for the given * tenant. * * @param tenantDomain tenant domain to register the application * @return OAuthApplicationInfo object with clientId, clientSecret and client name of the registered OAuth app * @throws APIManagementException if an error occurs while registering application */ private static OAuthApplicationInfo registerKeyMgtApplication(String tenantDomain, String keyManagerServiceUrl, String username, String password) throws APIManagementException { OAuthApplicationInfo oAuthApplicationInfo = null; String clientName = APIConstants.KEY_MANAGER_CLIENT_APPLICATION_PREFIX + tenantDomain; if (StringUtils.isEmpty(keyManagerServiceUrl)) { throw new APIManagementException("API Key Validator Server URL cannot be empty or null"); } String dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]; dcrEndpoint += APIConstants.RestApiConstants.DYNAMIC_CLIENT_REGISTRATION_URL_SUFFIX; try { HttpPost httpPost = new HttpPost(dcrEndpoint); httpPost.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader(username, password)); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, APIConstants.APPLICATION_JSON_MEDIA_TYPE); // Create DCR request payload KMRegisterProfileDTO kmRegisterProfileDTO = new KMRegisterProfileDTO(); kmRegisterProfileDTO.setClientName(clientName); kmRegisterProfileDTO.setOwner(APIUtil.getTenantAdminUserName(tenantDomain)); kmRegisterProfileDTO.setGrantType(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS); StringEntity payload = new StringEntity(new Gson().toJson(kmRegisterProfileDTO)); httpPost.setEntity(payload); if (log.isDebugEnabled()) { log.debug("Invoking DCR REST API of KM: " + dcrEndpoint + " to register application " + clientName); } java.net.URL keyManagerURL = new java.net.URL(keyManagerServiceUrl); int keyManagerPort = keyManagerURL.getPort(); String keyManagerProtocol = keyManagerURL.getProtocol(); try (CloseableHttpClient httpClient = (CloseableHttpClient) APIUtil .getHttpClient(keyManagerPort, keyManagerProtocol)) { try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { try (InputStream inputStream = httpResponse.getEntity().getContent()) { String responseContent = IOUtils.toString(inputStream); if (StringUtils.isNotEmpty(responseContent)){ oAuthApplicationInfo = new Gson().fromJson(responseContent, OAuthApplicationInfo.class); } } } else { throw new APIManagementException("Error occurred while registering application: " + clientName + " " + "via " + dcrEndpoint + ". Error Status: " + statusCode ); } } } } catch (IOException e) { String errorMessage = "Error occurred while registering application: " + clientName + " via " + dcrEndpoint; throw new APIManagementException(errorMessage, e); } return oAuthApplicationInfo; }
Example 14
Source File: TokenRevocationNotifierImpl.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * Method to send the revoked token to the persistent storage * * @param revokedToken token to be revoked * @param properties persistent notifier properties read from the config */ @Override public void sendMessageToPersistentStorage(String revokedToken, Properties properties) { //Variables related to Persistent Notifier String DEFAULT_PERSISTENT_NOTIFIER_HOSTNAME = "https://localhost:2379/v2/keys/jti/"; String persistentNotifierHostname = properties .getProperty("hostname", DEFAULT_PERSISTENT_NOTIFIER_HOSTNAME); String persistentNotifierTTL = properties.getProperty("ttl", DEFAULT_TTL); String DEFAULT_PERSISTENT_NOTIFIER_USERNAME = "root"; String persistentNotifierUsername = properties .getProperty("username", DEFAULT_PERSISTENT_NOTIFIER_USERNAME); String DEFAULT_PERSISTENT_NOTIFIER_PASSWORD = "root"; String persistentNotifierPassword = properties .getProperty("password", DEFAULT_PERSISTENT_NOTIFIER_PASSWORD); String etcdEndpoint = persistentNotifierHostname + revokedToken; URL etcdEndpointURL = new URL(etcdEndpoint); String etcdEndpointProtocol = etcdEndpointURL.getProtocol(); int etcdEndpointPort = etcdEndpointURL.getPort(); HttpClient etcdEPClient = APIUtil.getHttpClient(etcdEndpointPort, etcdEndpointProtocol); HttpPut httpETCDPut = new HttpPut(etcdEndpoint); byte[] encodedAuth = Base64.encodeBase64((persistentNotifierUsername + ":" + persistentNotifierPassword). getBytes(StandardCharsets.UTF_8)); String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.UTF_8); httpETCDPut.setHeader(HttpHeaders.AUTHORIZATION, authHeader); List<NameValuePair> etcdParams = new ArrayList<>(2); etcdParams.add(new BasicNameValuePair("value", "true")); etcdParams.add(new BasicNameValuePair("ttl", persistentNotifierTTL)); //Send the revoked token to the persistent storage Server httpETCDPut.setEntity(new UrlEncodedFormEntity(etcdParams, StandardCharsets.UTF_8)); HttpResponse etcdResponse; try { etcdResponse = etcdEPClient.execute(httpETCDPut); if (etcdResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK || etcdResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { if (log.isDebugEnabled()) { log.debug("Successfully submitted the request for revoked token. HTTP status :" + etcdResponse .getStatusLine().getStatusCode()); } } else { log.error("Sending revoked token to persistent storage failed. HTTP error code : " + etcdResponse .getStatusLine().getStatusCode()); } } catch (IOException e) { log.error("Error while sending revoked token to the persistent storage :", e); } }
Example 15
Source File: SubscriptionDataLoaderImpl.java From carbon-apimgt with Apache License 2.0 | 4 votes |
private String invokeService(String path, String tenantDomain) throws DataLoadingException, IOException { String serviceURLStr = getEventHubConfigurationDto.getServiceUrl(); HttpGet method = new HttpGet(serviceURLStr + path); URL serviceURL = new URL(serviceURLStr + path); byte[] credentials = getServiceCredentials(getEventHubConfigurationDto); 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 = false; do { try { httpResponse = httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < retrievalRetries) { retry = true; log.warn("Failed retrieving " + path + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + retrievalTimeoutInSeconds + " seconds."); try { Thread.sleep(retrievalTimeoutInSeconds * 1000); } catch (InterruptedException e) { // Ignore } } else { throw ex; } } } while (retry); if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) { log.error("Could not retrieve subscriptions for tenantDomain : " + tenantDomain); throw new DataLoadingException("Error while retrieving subscription from " + path); } String responseString = EntityUtils.toString(httpResponse.getEntity(), UTF8); if (log.isDebugEnabled()) { log.debug("Response : " + responseString); } return responseString; }