Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.application.authentication.endpoint.util.bean.UserDTO;
import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade;
import org.wso2.carbon.identity.core.HTTPClientManager;
import org.wso2.carbon.identity.core.ServiceURLBuilder;
import org.wso2.carbon.identity.core.URLBuilderException;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
Expand Down Expand Up @@ -375,11 +376,15 @@ private static String buildAbsoluteURL(String contextPath) throws URLBuilderExce
*/
public static String sendGetRequest(String backendURL) {

try (CloseableHttpClient httpclient = HTTPClientUtils.createClientWithCustomHostnameVerifier().build()) {
return HTTPClientManager.executeWithHttpClient(httpClient ->
sendGetRequest(backendURL, httpClient));
}

private static String sendGetRequest(String backendURL, CloseableHttpClient httpclient) {

try {
HttpGet httpGet = new HttpGet(backendURL);
setAuthorizationHeader(httpGet);

return httpclient.execute(httpGet, response -> {
if (log.isDebugEnabled()) {
log.debug("HTTP status " + response.getCode() +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.wso2.carbon.identity.application.authentication.endpoint.util.client.model.AuthenticationErrorResponse;
import org.wso2.carbon.identity.application.authentication.endpoint.util.client.model.AuthenticationResponse;
import org.wso2.carbon.identity.application.authentication.endpoint.util.client.model.AuthenticationSuccessResponse;
import org.wso2.carbon.identity.core.HTTPClientManager;
import org.wso2.carbon.utils.httpclient5.HTTPClientUtils;

import java.io.BufferedReader;
Expand Down Expand Up @@ -81,8 +82,14 @@ public AuthenticationResponse authenticate(String username, Object password) thr
HttpPost httpPostRequest = new HttpPost(endpointURL);
httpPostRequest.setHeader(HttpHeaders.AUTHORIZATION, buildBasicAuthHeader(username, password));
httpPostRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
return HTTPClientManager.executeWithHttpClient(httpClient ->
authenticate(httpClient, httpPostRequest, endpointURL));
}

private AuthenticationResponse authenticate(CloseableHttpClient httpClient, HttpPost httpPostRequest,
String endpointURL) throws ServiceClientException {

try (CloseableHttpClient httpClient = HTTPClientUtils.createClientWithCustomHostnameVerifier().build()) {
try {
return httpClient.execute(httpPostRequest, response -> {

String responseString;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.carbon.identity.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.utils.httpclient5.HTTPClientUtils;

import java.io.IOException;

/**
* Manage HTTP client creation with pool.
*/
public class HTTPClientManager {

public static final String HTTP_CLIENT_MAX_TOTAL_CONNECTIONS = "HttpClient.ConnectionPool.MaxTotalConnections";
public static final String HTTP_CLIENT_DEFAULT_MAX_CONNECTIONS_PER_ROUTE =
"HttpClient.ConnectionPool.DefaultMaxConnectionsPerRoute";
public static final String HTTP_CLIENT_ADD_KEEP_ALIVE_STRATEGY =
"HttpClient.ConnectionPool.AddKeepAliveStrategy";
public static final String HTTP_CLIENT_POOL_ENABLED = "HttpClient.ConnectionPool.Enabled";

private static final Log log = LogFactory.getLog(HTTPClientManager.class);
private static final CloseableHttpClient httpClient;
private static final boolean isConnectionPoolEnabled;

private HTTPClientManager() {
}

static {

isConnectionPoolEnabled = Boolean.parseBoolean(
ServerConfiguration.getInstance().getFirstProperty(HTTP_CLIENT_POOL_ENABLED));

HttpClientBuilder clientBuilder = HTTPClientUtils.createClientWithCustomHostnameVerifier();

if (isConnectionPoolEnabled) {

String maxTotalConnectionProp = ServerConfiguration.getInstance()
.getFirstProperty(HTTP_CLIENT_MAX_TOTAL_CONNECTIONS);
String defaultMaxPerRouteProp = ServerConfiguration.getInstance()
.getFirstProperty(HTTP_CLIENT_DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
String addKeepAliveStrategy = ServerConfiguration.getInstance()
.getFirstProperty(HTTP_CLIENT_ADD_KEEP_ALIVE_STRATEGY);

int maxTotalConnections = 100;
int defaultMaxPerRoute = 100;

if (maxTotalConnectionProp != null) {
try {
maxTotalConnections = Integer.parseInt(maxTotalConnectionProp);
} catch (NumberFormatException ignore) {
log.debug("Parsing issue for maxTotalConnections property: " + maxTotalConnectionProp);
}
}
if (defaultMaxPerRouteProp != null) {
try {
defaultMaxPerRoute = Integer.parseInt(defaultMaxPerRouteProp);
} catch (NumberFormatException ignore) {
log.debug("Parsing issue for defaultMaxPerRoute property: " + defaultMaxPerRouteProp);
}
}
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(maxTotalConnections);
connManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
clientBuilder.setConnectionManager(connManager);
if (Boolean.parseBoolean(addKeepAliveStrategy)) {
clientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
}
}
httpClient = clientBuilder.build();
}

public static CloseableHttpClient getHttpClient() {

return httpClient;
}

/**
* Executes an operation with appropriate HttpClient management.
* Handles both pooled and non-pooled clients, ensuring proper cleanup.
*
* @param operation The operation to execute with the HttpClient
* @param <T> Return type of the operation
* @param <E> Exception type that the operation may throw
* @return Result of the operation
* @throws E if operation fails
*/
public static <T, E extends Exception> T executeWithHttpClient(HttpClientOperation<T, E> operation)
throws E {

boolean usePooling = isConnectionPoolEnabled;
CloseableHttpClient httpClient = usePooling ? getHttpClient()
: HTTPClientUtils.createClientWithCustomHostnameVerifier().build();

try {
return operation.execute(httpClient);
} finally {
closeHttpClientIfNeeded(httpClient);
}
}

/**
* Closes HttpClient only if not using connection pooling.
*
* @param httpClient The client to close
*/
private static void closeHttpClientIfNeeded(CloseableHttpClient httpClient) {

if (!isConnectionPoolEnabled) {
try {
httpClient.close();
} catch (IOException e) {
log.debug("Failed to close non-pooled HttpClient", e);
}
}
}

public static boolean isConnectionPoolEnabled() {

return isConnectionPoolEnabled;
}

/**
* Functional interface for operations that use HttpClient.
* Generalized to work with any exception type.
*
* @param <T> Return type of the operation
* @param <E> Exception type that may be thrown
*/
@FunctionalInterface
public interface HttpClientOperation<T, E extends Exception> {

T execute(CloseableHttpClient httpClient) throws E;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.wso2.carbon.core.SameSiteCookie;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.core.HTTPClientManager;
import org.wso2.carbon.identity.core.ServiceURLBuilder;
import org.wso2.carbon.identity.core.URLBuilderException;
import org.wso2.carbon.identity.core.model.CookieBuilder;
Expand Down Expand Up @@ -1049,7 +1050,10 @@ private static void updateCookieConfig(CookieBuilder cookieBuilder, IdentityCook
*/
public static String getHttpClientResponseString(HttpUriRequestBase request) throws IOException {

try (CloseableHttpClient httpClient = HTTPClientUtils.createClientWithCustomHostnameVerifier().build()) {
CloseableHttpClient httpClient = HTTPClientManager.isConnectionPoolEnabled() ?
HTTPClientManager.getHttpClient() :
HTTPClientUtils.createClientWithCustomHostnameVerifier().build();
try {
return httpClient.execute(request, response -> {
if (response.getCode() == HttpStatus.SC_OK) {
try (InputStream inputStream = response.getEntity().getContent();
Expand All @@ -1066,6 +1070,10 @@ public static String getHttpClientResponseString(HttpUriRequestBase request) thr
}
return null;
});
} finally {
if (!HTTPClientManager.isConnectionPoolEnabled()) {
httpClient.close();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ public boolean checkPreference(String tenant, String connectorName, String prope
public boolean checkMultiplePreference(String tenant, String connectorName, List<String> propertyNames)
throws PreferenceRetrievalClientException {

try (CloseableHttpClient httpclient = HTTPClientUtils.createClientWithCustomHostnameVerifier().build()) {
try {
JSONArray requestBody = new JSONArray();
JSONObject preference = new JSONObject();
preference.put(CONNECTOR_NAME, connectorName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.wso2.carbon.identity.core.HTTPClientManager;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointConstants;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointUtil;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementServiceUtil;
Expand Down Expand Up @@ -229,12 +230,20 @@ public JSONObject checkUsernameValidityStatus(User user, boolean skipSignUpCheck
private JSONObject checkUserNameValidityInternal(User user, boolean skipSignUpCheck) throws
SelfRegistrationMgtClientException {

return HTTPClientManager.executeWithHttpClient(httpClient ->
checkUserNameValidityInternal(user, skipSignUpCheck, httpClient));
}

private JSONObject checkUserNameValidityInternal(User user, boolean skipSignUpCheck,
CloseableHttpClient httpclient)
throws SelfRegistrationMgtClientException {

if (log.isDebugEnabled()) {
log.debug("Checking username validating for username: " + user.getUsername()
+ ". SkipSignUpCheck flag is set to " + skipSignUpCheck);
}

try (CloseableHttpClient httpclient = HTTPClientUtils.createClientWithCustomHostnameVerifier().build()) {
try {
JSONObject userObject = new JSONObject();
userObject.put(USERNAME, user.getUsername());

Expand Down