Handle connection errors while calling the backend API
@@ -35,6 +35,8 @@ import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.mgt.endpoint.IdentityManagementEndpointConstants;
import org.wso2.carbon.identity.mgt.endpoint.IdentityManagementEndpointUtil;
import org.wso2.carbon.identity.mgt.endpoint.IdentityManagementServiceUtil;
@@ -51,6 +53,8 @@ import java.util.*;
import java.util.Map.Entry;
public class ApiClient {
+ private static final Log log = LogFactory.getLog(ApiClient.class);
+
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = IdentityManagementEndpointUtil.buildEndpointUrl(IdentityManagementEndpointConstants
.UserInfoRecovery.RECOVERY_API_RELATIVE_PATH);
@@ -444,6 +448,10 @@ public class ApiClient {
throw new ApiException(500, "Cannot have body and form params");
}
+ if(!isRequestMethodSupported(method, GET, POST, PUT, DELETE, PATCH)) {
+ throw new ApiException(500, "unknown method type " + method);
+ }
+
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null) {
@@ -461,12 +469,13 @@ public class ApiClient {
}
}
- ClientResponse response;
String toEncode = IdentityManagementServiceUtil.getInstance().getAppName() + ":"
+ String.valueOf(IdentityManagementServiceUtil.getInstance().getAppPassword());
byte[] encoding = Base64.encodeBase64(toEncode.getBytes());
String authHeader = new String(encoding, Charset.defaultCharset());
+ try {
+ ClientResponse response = null;
if (GET.equals(method)) {
response = (ClientResponse) builder.header(AUTHORIZATION, CLIENT + authHeader).get(ClientResponse.class);
} else if (POST.equals(method)) {
@@ -482,10 +491,14 @@ public class ApiClient {
response = builder.type(contentType).header(X_HTTP_METHOD_OVERRIDE, PATCH).header
(AUTHORIZATION, CLIENT + authHeader).post
(ClientResponse.class, serialize(body, contentType, formParams));
- } else {
- throw new ApiException(500, "unknown method type " + method);
}
return response;
+ } catch (Exception e) {
+ String errMsg = String.format("Error while performing the request method: %s on the " +
+ "resource: %s", method, url) ;
+ log.error(errMsg, e);
+ throw new ApiException(500, "Error while accessing the backend service");
+ }
}
/**
@@ -538,6 +551,13 @@ public class ApiClient {
}
}
+ private boolean isRequestMethodSupported(String method, String GET, String POST, String PUT, String DELETE,
+ String PATCH) {
+
+ return GET.equals(method) || POST.equals(method) || PUT.equals(method) || DELETE.equals(method)
+ || PATCH.equals(method);
+ }
+
/**
* Encode the given form parameters as request body.
