From 41a0c9118ab5413929a20bd8e8635aeecbc1229d Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Tue, 12 Apr 2022 18:02:45 +0530 Subject: [PATCH] Add java doc comments Use try-with resource when using CloseableHttpClient Refactor few variable and method names --- .../IdentityServerManagementException.java | 6 + .../common/services/ApplicationManager.java | 52 ++++++++- .../impl/WSO2IAMSPApplicationService.java | 51 +++++--- .../mgt/core/impl/ApplicationManagerImpl.java | 55 +++++++-- .../core/impl/SPApplicationManagerImpl.java | 80 ++++++++++++- .../impl/SPApplicationServiceImpl.java | 6 +- .../device/mgt/core/common/util/FileUtil.java | 27 ++++- .../device/mgt/core/common/util/HttpUtil.java | 110 ++++++++++++++++-- 8 files changed, 339 insertions(+), 48 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java index 602a8eddee..f2168ec32b 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java @@ -21,6 +21,12 @@ package io.entgra.application.mgt.common.exception; * Exception that will be thrown if any error occurs while calling identity server services . */ public class IdentityServerManagementException extends ApplicationManagementException { + + public IdentityServerManagementException(String message, Throwable throwable) { + super(message, throwable); + setMessage(message); + } + public IdentityServerManagementException(String message) { super(message); setMessage(message); diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java index e59021d1e4..00c5b4f9e9 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java @@ -100,6 +100,12 @@ public interface ApplicationManager { */ ApplicationDTO uploadReleaseArtifactIfExist(T app) throws ApplicationManagementException; + /** + * Check if public app release packageName is valid (I.E invalid if packageName already exists) + * + * @param packageName name of the application release package + * @throws ApplicationManagementException if package name is invalid + */ void validatePublicAppReleasePackageName(String packageName) throws ApplicationManagementException; /** @@ -169,6 +175,13 @@ public interface ApplicationManager { */ void deleteApplicationRelease(String releaseUuid) throws ApplicationManagementException; + /** + * Use to delete application artifact files (For example this is useful to delete application release artifacts + * (I.E screenshots) when an application is deleted) + * + * @param directoryPaths directory paths that contains release artifacts (I.E screenshots) + * @throws ApplicationManagementException if error occurred while deleting artifacts + */ void deleteApplicationArtifacts(List directoryPaths) throws ApplicationManagementException; /** @@ -220,6 +233,13 @@ public interface ApplicationManager { ApplicationType type) throws ApplicationManagementException; + /** + * Get application and all application releases associated to the application for the given application Id + * + * @param applicationId Application Id + * @return {@link ApplicationDTO} + * @throws ApplicationManagementException if error occurred application data from the database. + */ ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException; /** @@ -292,7 +312,8 @@ public interface ApplicationManager { void updateApplicationArtifact(String deviceType, String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /*** + /** + * Use to update existing enterprise app release * * @param releaseUuid UUID of the application release. * @param entAppReleaseWrapper {@link ApplicationReleaseDTO} @@ -302,22 +323,47 @@ public interface ApplicationManager { ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + + /** + * Use to update existing public app release + * + * @param releaseUuid UUID of the application release. + * @param publicAppReleaseWrapper {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return If the application release is updated correctly True returns, otherwise retuen False + */ ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + /** + * Use to update existing web app release + * + * @param releaseUuid UUID of the application release. + * @param webAppReleaseWrapper {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return If the application release is updated correctly True returns, otherwise retuen False + */ ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + /** + * Use to update existing custom app release + * + * @param releaseUuid UUID of the application release. + * @param customAppReleaseWrapper {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return If the application release is updated correctly True returns, otherwise retuen False + */ ApplicationRelease updateCustomAppRelease(String releaseUuid, CustomAppReleaseWrapper customAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /*** + /** * To validate the application creating request * */ void validateAppCreatingRequest(T param) throws ApplicationManagementException, RequestValidatingException; - /*** + /** * * @throws ApplicationManagementException throws if payload does not satisfy requirements. */ diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java index 7e72576e40..2dc5a91e27 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java @@ -65,8 +65,7 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication String uriString = constructAPIUrl(identityServer); uriString += Constants.FORWARD_SLASH + spAppId; req.setURI(HttpUtil.createURI(uriString)); - CloseableHttpClient client = HttpClients.createDefault(); - try { + try (CloseableHttpClient client = HttpClients.createDefault()) { HttpResponse response = invokeISAPI(identityServer, client, req); String responseBody = HttpUtil.getResponseString(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { @@ -82,16 +81,17 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication } catch (IOException e) { String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running"; log.error(msg, e); - throw new IdentityServerManagementException(msg); - } finally { - try { - client.close(); - } catch (IOException e) { - log.error("Error occurred while closing http connection"); - } + throw new IdentityServerManagementException(msg, e); } } + /** + * Construct error message string depending on service providers api response + * (I.E If unauthorized a different message will be returned) + * + * @param response of the service provider api call + * @return constructed error message + */ private String constructErrorMessage(HttpResponse response) { String msg = "Error occurred while calling SP Applications API"; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { @@ -109,8 +109,7 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication uriString += Constants.QUERY_STRING_SEPARATOR + Constants.OFFSET_QUERY_PARAM + Constants.QUERY_KEY_VALUE_SEPARATOR + offset; req.setURI(HttpUtil.createURI(uriString)); - CloseableHttpClient client = HttpClients.createDefault(); - try { + try (CloseableHttpClient client = HttpClients.createDefault()) { HttpResponse response = invokeISAPI(identityServer, client, req); String responseBody = HttpUtil.getResponseString(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { @@ -123,27 +122,43 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication } catch (IOException e) { String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running"; log.error(msg, e); - throw new IdentityServerManagementException(msg); - } finally { - try { - client.close(); - } catch (IOException e) { - log.error("Error occurred while closing http connection"); - } + throw new IdentityServerManagementException(msg, e); } } + /** + * Takes essential prerequisite steps (I.E setting authorization header), + * invokes provided GET request and returns the response + * + * @param identityServer {@link IdentityServerDTO} + * @param client httpClient that should be used to invoke + * @param request GET request to be invoked + * @return response of the invoked api + */ private HttpResponse invokeISAPI(IdentityServerDTO identityServer, HttpClient client, HttpGet request) throws IOException { setBasicAuthHeader(identityServer, request); return client.execute(request); } + /** + * Add basic auth header to provided service provider api request by getting the username and password + * from identity server bean + * + * @param identityServer {@link IdentityServerDTO} + * @param request service provider api request + */ private void setBasicAuthHeader(IdentityServerDTO identityServer, HttpRequestBase request) { String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUsername(), identityServer.getPassword()); request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); } + /** + * Helps to construct service provider api base url + * + * @param identityServer {@link IdentityServerDTO} + * @return constructed service providers api url + */ private String constructAPIUrl(IdentityServerDTO identityServer) { String identityServerUrl = identityServer.getUrl(); // add "/" at the end, if the server url doesn't contain "/" at the end diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java index ffdd342c78..fc928a1e97 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java @@ -341,6 +341,14 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Use to upload/save web app release artifacts (I.E icon) + * + * @param releaseDTO {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return constructed {@link ApplicationReleaseDTO} with upload details + * @throws ResourceManagementException if error occurred while uploading + */ private ApplicationReleaseDTO uploadWebAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact) throws ResourceManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); @@ -350,6 +358,15 @@ public class ApplicationManagerImpl implements ApplicationManager { return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); } + /** + * Use to upload/save public app release artifacts (I.E icon) + * + * @param releaseDTO {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @param deviceType Device Type name + * @return constructed {@link ApplicationReleaseDTO} with upload details + * @throws ResourceManagementException if error occurred while uploading + */ private ApplicationReleaseDTO uploadPubAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, String deviceType) throws ResourceManagementException { @@ -384,6 +401,15 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Use to upload/save public app release artifacts (I.E icon) + * + * @param releaseDTO {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @param deviceType Device Type name + * @return constructed {@link ApplicationReleaseDTO} with upload details + * @throws ResourceManagementException if error occurred while uploading + */ private ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, String deviceType) throws ResourceManagementException, ApplicationManagementException { @@ -402,7 +428,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } catch (IOException e) { String msg = "Error occurred when uploading release artifact into the server"; log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); } @@ -436,16 +462,32 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Helps to byte content of release binary file of application artifact + * This method can be useful when uploading application release binary file or when generating md5hex of release binary + * + * @param artifact {@link ApplicationArtifact} + * @return byte content of application release binary file + * @throws ApplicationManagementException if error occurred while getting byte content + */ private byte[] getByteContentOfApp(ApplicationArtifact artifact) throws ApplicationManagementException{ try { return IOUtils.toByteArray(artifact.getInstallerStream()); } catch (IOException e) { String msg = "Error occurred while getting byte content of app binary artifact"; log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } } + /** + * Useful to generate md5hex string of application release + * + * @param applicationArtifact {@link ApplicationArtifact} + * @param content byte array content of application release binary file + * @return Generated md5hex string + * @throws ApplicationManagementException if any error occurred while generating md5hex string + */ private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException { try { String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); @@ -458,7 +500,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } catch( ApplicationStorageManagementException e) { String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName(); log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } } @@ -1197,13 +1239,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - /** - * Get Application and all application releases associated to the application that has given application Id - * - * @param applicationId Application Id - * @return {@link ApplicationDTO} - * @throws ApplicationManagementException if error occurred application data from the databse. - */ @Override public ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index 3f57661640..6f8fd98198 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -80,6 +80,13 @@ public class SPApplicationManagerImpl implements SPApplicationManager { return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); } + /** + * This is similar to getIdentityServerFromDB method except throws {@link NotFoundException} if identity server + * does not exist for the given id + * + * @param identityServerId id of identity server + * @return {@link IdentityServerDTO} + */ private IdentityServerDTO getIdentityServer(int identityServerId) throws ApplicationManagementException { IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId); if (identityServerDTO == null) { @@ -90,6 +97,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { return identityServerDTO; } + /** + * Use to get {@link IdentityServerDTO} bean from database. Returns null if does not exist + * + * @param identityServerId id of identity server + * @return {@link IdentityServerDTO} + */ private IdentityServerDTO getIdentityServerFromDB(int identityServerId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -191,6 +204,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * Validate the identity server delete request + * + * @param identityServerId identity server id + * @throws BadRequestException if provided identity server id is invalid + */ private void validateIdentityServerDeleteRequest(int identityServerId) throws ApplicationManagementException { IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId); if (identityServerDTO == null) { @@ -200,6 +219,15 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * This method is useful to re-construct the api params Map using updated identity server bean {@link IdentityServerDTO} + * For example updated identity server bean may contain only updated api param, in which case the existing api param values + * should be re-added to updated identity server bean + * + * @param updatedIdentityServerDTO updated identity server request payload + * @param existingIdentityServerDTO corresponding existing identity server of updated identity server + * @return Constructed api param map + */ private Map constructUpdatedApiParams(IdentityServerDTO updatedIdentityServerDTO, IdentityServerDTO existingIdentityServerDTO) { Map updatedApiParams = updatedIdentityServerDTO.getApiParams(); @@ -292,6 +320,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { validateIdentityServerUrl(identityServerDTO.getUrl()); } + /** + * Validate provided identity server url (For example make sure it uses http/https protocol) + * + * @param url url of the identity server + * @throws BadRequestException if url is invalid + */ private void validateIdentityServerUrl(String url) throws BadRequestException { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS); @@ -302,17 +336,32 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } - private void validateUpdateIdentityServerRequestApiParam(IdentityServerDTO identityServerUpdateDTO, + /** + * Validate provided api params map in a identity server updated request + * For example the updated api param map may not contain all the required api params + * + * @param updatedIdentityServerDto Identity server update request payload bean + * @param existingIdentityServerDTO Corresponding existing identity server bean of the updated identity server + * @throws ApplicationManagementException if any api param is invalid + */ + private void validateUpdateIdentityServerRequestApiParam(IdentityServerDTO updatedIdentityServerDto, IdentityServerDTO existingIdentityServerDTO) throws ApplicationManagementException { ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(existingIdentityServerDTO.getProviderName()); List requiredApiParams = serviceProviderApplicationService.getRequiredApiParams(); - if (!identityServerUpdateDTO.getProviderName().equals(existingIdentityServerDTO.getProviderName())) { - validateAllRequiredParamsExists(identityServerUpdateDTO, requiredApiParams); + if (!updatedIdentityServerDto.getProviderName().equals(existingIdentityServerDTO.getProviderName())) { + validateAllRequiredParamsExists(updatedIdentityServerDto, requiredApiParams); } - validateIfAnyInvalidParamExists(identityServerUpdateDTO, requiredApiParams); + validateIfAnyInvalidParamExists(updatedIdentityServerDto, requiredApiParams); } + /** + * Validate api params map of identity server create request payload + * For example the api param map may not contain all the required api params + * + * @param identityServerDTO {@link IdentityServerDTO} + * @throws ApplicationManagementException if any api param is invalid + */ private void validateCreateIdentityServerRequestApiParams(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(identityServerDTO.getProviderName()); @@ -321,6 +370,13 @@ public class SPApplicationManagerImpl implements SPApplicationManager { validateIfAnyInvalidParamExists(identityServerDTO, requiredApiParams); } + /** + * Make sure if all required api params exists for the given identity server bean + * + * @param identityServerDTO {@link IdentityServerDTO} + * @param requiredApiParams all mandatory api params + * @throws BadRequestException if a required api param does not exist + */ private void validateAllRequiredParamsExists(IdentityServerDTO identityServerDTO, List requiredApiParams) throws BadRequestException { for (String param : requiredApiParams) { @@ -333,6 +389,14 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * Make sure if all api params are valid + * For example it may contain an unwanted api param + * + * @param identityServerDTO {@link IdentityServerDTO} + * @param requiredApiParams all required api params + * @throws BadRequestException if an unwanted api param exist + */ private void validateIfAnyInvalidParamExists(IdentityServerDTO identityServerDTO, List requiredApiParams) throws BadRequestException { for (String param : identityServerDTO.getApiParamKeys()) { @@ -344,6 +408,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * If the given providerName does not exist in the identity server config file + * + * @param providerName Name of the identity service provider + * @return if provider name exist in identity server config + */ private boolean isIdentityServiceProviderNotConfigured(String providerName) { List identityServiceProviders = ConfigurationManager.getInstance().getIdentityServerConfiguration(). getIdentityServiceProviders(); @@ -508,7 +578,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } catch (ApplicationManagementException e) { String msg = "Identity service provider configuration file is invalid. Hence failed to proceed."; log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } } return identityServiceProviderDTOS; diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index c13a12e320..cceefb6c18 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -95,7 +95,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).entity("Successfully deleted identity server").build(); } catch (NotFoundException e) { String msg = "Identity server with the id " + id + " does not exist."; - log.error(msg); + log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; @@ -114,7 +114,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).entity(identityServer).build(); } catch (NotFoundException e) { String msg = "Identity server with the id " + id + " does not exist."; - log.error(msg); + log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; @@ -133,7 +133,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).entity(identityServerResponse).build(); } catch (NotFoundException e) { String msg = "Identity server with the id " + id + " does not exist."; - log.error(msg); + log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (BadRequestException e) { String errMsg = "Identity server request payload is invalid"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java index dc9ce7cc58..d90e586412 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java @@ -24,6 +24,12 @@ import java.util.Base64; public class FileUtil { + /** + * Useful to remove path separator string "," from base64 string + * + * @param base64String base64 string + * @return base64 string without path separator + */ public static String removePathSeparatorFromBase64String(String base64String) { String partSeparator = ","; if (base64String.contains(partSeparator)) { @@ -32,6 +38,12 @@ public class FileUtil { return base64String; } + /** + * Useful to convert base64 string to input stream + * + * @param base64 base64 string to be converted + * @return {@link InputStream} of the provided base64 string + */ public static InputStream base64ToInputStream(String base64) { base64 = FileUtil.removePathSeparatorFromBase64String(base64); byte[] base64Bytes = Base64.getDecoder().decode(base64); @@ -72,13 +84,24 @@ public class FileUtil { return suffix; } + /** + * Use to extract file extension from file name + * + * @param fileName name of the file + * @return extension of the file + */ private static String extractFileExtension(String fileName) { return fileName.substring(fileName.lastIndexOf('.') + 1); } + /** + * Use to extract the file name without the extension + * For example if you provide "main.java" as the fileName this will return main + * + * @param fileName name of the file + * @return file name without file extension + */ private static String extractFileNameWithoutExtension(String fileName) { return fileName.substring(0, fileName.lastIndexOf('.')); } - - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java index 05db183b2a..afd8ad5f44 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java @@ -32,20 +32,47 @@ import java.util.Map; public class HttpUtil { + /** + * Use to create {@link URI} from string + * This does encoding of the provided uri string before creating the URI + * + * @param uriString uri string to be used to create the URI + * @return created URI + */ public static URI createURI(String uriString) { uriString = uriString.replace(" ", "%20"); return URI.create(uriString); } + /** + * Use to create basic auth header string for provided credentials + * + * @param userName username credential + * @param password password credential + * @return Basic auth header + */ public static String getBasicAuthBase64Header(String userName, String password) { return Constants.BASIC_AUTH_HEADER_PREFIX + getBase64Encode(userName, password); } + /** + * Use to get the base64 encoded string of key value pair. + * For example this can be useful when creating basic auth header + * + * @return base64 encoded string of provided key and value + */ public static String getBase64Encode(String key, String value) { return new String(Base64.encodeBase64((key + ":" + value).getBytes())); } - public static String getRequestSubPathFromEnd(URI requestUri, int position) { + /** + * Useful to get the sub path in a position from the given uri starting from end of the uri + * + * @param requestUri {@link URI} + * @param position of which the sub path is needed + * @return Sub path of the uri + */ + public static String extractRequestSubPathFromEnd(URI requestUri, int position) { if (requestUri.getPath() != null) { String[] pathList = requestUri.getPath().split("/"); if (pathList.length - 1 >= position) { @@ -55,8 +82,15 @@ public class HttpUtil { return null; } - public static String getRequestSubPath(String fullPath, int position) { - String[] pathList = fullPath.split("/"); + /** + * Useful to get the sub path in a position from the given uri + * + * @param uri uri string from which the sub path should be extracted + * @param position of which the sub path is needed + * @return Sub path of the uri + */ + public static String extractRequestSubPath(String uri, int position) { + String[] pathList = uri.split("/"); if (pathList.length - 1 > position) { String path = pathList[position + 1]; if(path.contains(Constants.URI_QUERY_SEPARATOR)) { @@ -67,14 +101,37 @@ public class HttpUtil { return null; } + /** + * This returns the response body as string + * + * @param response {@link HttpResponse} + * @return Response body string + * @throws IOException if errors while converting response body to string + */ public static String getResponseString(HttpResponse response) throws IOException { return EntityUtils.toString(response.getEntity()); } - public static boolean isQueryParamExist(String param, URI request) { - Map> queryMap = getQueryMap(request); + /** + * Useful to check if a given query param exists in uri + * + * @param param query param to be checked + * @param uri in which query param should be checked + * @return if the provided query parameter exists in uri + */ + public static boolean isQueryParamExist(String param, URI uri) { + Map> queryMap = getQueryMap(uri); return queryMap.containsKey(param); } + + /** + * This is useful to get first query parameter value from a query map. + * For example a query parameter may have multiple values. + * + * @param param query parameter of which the value is needed + * @param queryMap query map which contains query paramters and it's values + * @return First value of provided query parameter + */ public static String getFirstQueryValue(String param, Map> queryMap) { List valueList = queryMap.get(param); String firstValue = null; @@ -83,6 +140,20 @@ public class HttpUtil { } return firstValue; } + + /** + * This constructs a key/value Map from query string of the provided uri. + * In other words this will create a map with query parameters as keys and their + * values as values. + * + * For example if the uri contains "?bar=1&foo=2" this will return a map + * with bar and foo as keys and 1 and 2 as their values + * + * This is similar to getQueryMap(URI uri) method except that this accepts uri string + * + * @param uri of which the query map to be created + * @return Query map of the provided uri + */ public static Map> getQueryMap(String uri) { String query = getQueryFromURIPath(uri); Map> map = new HashMap<>(); @@ -103,8 +174,20 @@ public class HttpUtil { } return map; } - public static Map> getQueryMap(URI request) { - String query = request.getQuery(); + + /** + * This constructs a key/value Map from query string of the provided uri. + * In other words this will create a map with query parameters as keys and their + * values as values. + * + * For example if the uri contains "?bar=1&foo=2" this will return a map + * with bar and foo as keys and 1 and 2 as their values + * + * @param uri of which the query map to be created + * @return Query map of the provided uri + */ + public static Map> getQueryMap(URI uri) { + String query = uri.getQuery(); Map> map = new HashMap<>(); if (query != null) { String[] params = query.split("&"); @@ -123,6 +206,13 @@ public class HttpUtil { } return map; } + + /** + * Get query string from uri path. Return null if no query string exists + * + * @param uri of which query string should be taken + * @return Query string of the provided uri + */ public static String getQueryFromURIPath(String uri) { String query = null; if (uri.length() > "?".length() && uri.contains("?")) { @@ -134,6 +224,12 @@ public class HttpUtil { return query; } + /** + * Get content type of http response + * + * @param response {@link HttpResponse} + * @return Content type + */ public static String getContentType(HttpResponse response) { ContentType contentType = ContentType.getOrDefault(response.getEntity()); return contentType.getMimeType();