From 545ca7e2a234328f0f8d89a88b0268c2d8b6b69c Mon Sep 17 00:00:00 2001 From: Ace Date: Mon, 23 Sep 2019 23:36:34 +0530 Subject: [PATCH 01/10] Changing status related APIs to honour tenant ID --- .../service/api/DeviceManagementService.java | 59 ++++++++++++------- .../impl/DeviceManagementServiceImpl.java | 39 ++++++++---- .../DeviceManagementProviderService.java | 6 +- .../DeviceManagementProviderServiceImpl.java | 11 ++-- 4 files changed, 75 insertions(+), 40 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index aba6d9819c..1aa36ca78f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -1627,7 +1627,7 @@ public interface DeviceManagementService { @Valid OperationRequest operationRequest); @GET - @Path("/status/count/{type}/{status}") + @Path("/status/count/{tenantDomain}/{type}/{status}") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -1653,16 +1653,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 304, message = "Not Modified. Empty body because the client already has the latest version" + - " of the requested resource.\n"), + " of the requested resource.\n"), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -1674,10 +1674,17 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while retrieving the device details.", + "Server error occurred while retrieving the device details.", response = ErrorResponse.class) }) Response getDeviceCountByStatus( + @ApiParam( + name = "tenantDomain", + value = "The tenant doamin.", + required = true) + @PathParam("tenantDomain") + @Size(max = 45) + String tenantDomain, @ApiParam( name = "type", value = "The device type name, such as ios, android, windows or fire-alarm.", @@ -1695,7 +1702,7 @@ public interface DeviceManagementService { @GET - @Path("/status/ids/{type}/{status}") + @Path("/status/ids/{tenantDomain}/{type}/{status}") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -1722,16 +1729,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 304, message = "Not Modified. Empty body because the client already has the latest version" + - " of the requested resource.\n"), + " of the requested resource.\n"), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -1743,10 +1750,17 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while retrieving the device details.", + "Server error occurred while retrieving the device details.", response = ErrorResponse.class) }) Response getDeviceIdentifiersByStatus( + @ApiParam( + name = "tenantDomain", + value = "The tenant domain.", + required = true) + @PathParam("tenantDomain") + @Size(max = 45) + String tenantDomain, @ApiParam( name = "type", value = "The device type name, such as ios, android, windows or fire-alarm.", @@ -1763,7 +1777,7 @@ public interface DeviceManagementService { String status); @PUT - @Path("/status/update/{type}/{status}") + @Path("/status/update/{tenantDomain}/{type}/{status}") @ApiOperation( produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON, @@ -1790,16 +1804,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource has been modified the last time.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), }), @ApiResponse( code = 304, message = "Not Modified. Empty body because the client already has the latest " + - "version of the requested resource."), + "version of the requested resource."), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -1811,13 +1825,16 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server Error. \n " + - "Server error occurred while retrieving information requested device.", + "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) - Response bulkUpdateDeviceStatus(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) - @PathParam("type") String type, - @ApiParam(name = "status", value = "The device type, such as ios, android or windows.", required = true) - @PathParam("status") String status, - @ApiParam(name = "deviceList", value = "The payload containing the new name of the device.", required = true) - @Valid List deviceList); + Response bulkUpdateDeviceStatus( + @ApiParam(name = "tenantDomain", value = "The tenant domain.", required = true) + @PathParam("tenantDomain") String tenantDomain, + @ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("type") String type, + @ApiParam(name = "status", value = "The device type, such as ios, android or windows.", required = true) + @PathParam("status") String status, + @ApiParam(name = "deviceList", value = "The payload containing the new name of the device.", required = true) + @Valid List deviceList); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 91770d28ea..2cc710d738 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -84,6 +84,7 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.validation.Valid; @@ -918,48 +919,66 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Override - @Path("/status/count/{type}/{status}") - public Response getDeviceCountByStatus(@PathParam("type") String type, @PathParam("status") String status) { + @Path("/status/count/{tenantDomain}/{type}/{status}") + public Response getDeviceCountByStatus(@PathParam("tenantDomain") String tenantDomain, @PathParam("type") String type, @PathParam("status") String status) { int deviceCount; try { - deviceCount = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCountOfTypeByStatus(type, status); + int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); + deviceCount = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCountOfTypeByStatus(tenantId, type, status); return Response.status(Response.Status.OK).entity(deviceCount).build(); } catch (DeviceManagementException e) { String errorMessage = "Error while retrieving device count."; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); + } catch (UserStoreException e) { + String errorMessage = "Error resolving tenant Domain"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); } } @GET @Override - @Path("/status/ids/{type}/{status}") - public Response getDeviceIdentifiersByStatus(@PathParam("type") String type, @PathParam("status") String status) { + @Path("/status/ids/{tenantDomain}/{type}/{status}") + public Response getDeviceIdentifiersByStatus(@PathParam("tenantDomain") String tenantDomain, @PathParam("type") String type, @PathParam("status") String status) { List deviceIds; try { - deviceIds = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceIdentifiersByStatus(type, status); + int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); + deviceIds = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceIdentifiersByStatus(tenantId, type, status); return Response.status(Response.Status.OK).entity(deviceIds.toArray(new String[0])).build(); } catch (DeviceManagementException e) { String errorMessage = "Error while obtaining list of devices"; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); + } catch (UserStoreException e) { + String errorMessage = "Error resolving tenant Domain"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); } } @PUT @Override - @Path("/status/update/{type}/{status}") - public Response bulkUpdateDeviceStatus(@PathParam("type") String type, @PathParam("status") String status, - @Valid List deviceList) { + @Path("/status/update/{tenantDomain}/{type}/{status}") + public Response bulkUpdateDeviceStatus(@PathParam("tenantDomain") String tenantDomain, @PathParam("type") String type, + @PathParam("status") String status, @Valid List deviceList) { try { - DeviceMgtAPIUtils.getDeviceManagementService().bulkUpdateDeviceStatus(type, deviceList, status); + int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); + DeviceMgtAPIUtils.getDeviceManagementService().bulkUpdateDeviceStatus(tenantId, type, deviceList, status); } catch (DeviceManagementException e) { String errorMessage = "Error while updating device status in bulk."; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); + } catch (UserStoreException e) { + String errorMessage = "Error resolving tenant Domain"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); } return Response.status(Response.Status.OK).build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 3b2012ac63..a9e3ed3d54 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -726,11 +726,11 @@ public interface DeviceManagementProviderService { List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, int geohashLength) throws DeviceManagementException; - int getDeviceCountOfTypeByStatus(String deviceType, String deviceStatus) throws DeviceManagementException; + int getDeviceCountOfTypeByStatus(int tenantId, String deviceType, String deviceStatus) throws DeviceManagementException; - List getDeviceIdentifiersByStatus(String deviceType, String deviceStatus) throws DeviceManagementException; + List getDeviceIdentifiersByStatus(int tenantId, String deviceType, String deviceStatus) throws DeviceManagementException; - boolean bulkUpdateDeviceStatus(String deviceType, List deviceList, String status) throws DeviceManagementException; + boolean bulkUpdateDeviceStatus(int tenantId, String deviceType, List deviceList, String status) throws DeviceManagementException; boolean updateEnrollment(String owner, List deviceIdentifiers) throws DeviceManagementException, UserNotFoundException, InvalidDeviceException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 7fec5a6333..b7109f55de 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -3035,8 +3035,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public int getDeviceCountOfTypeByStatus(String deviceType, String deviceStatus) throws DeviceManagementException { - int tenantId = this.getTenantId(); + public int getDeviceCountOfTypeByStatus(int tenantId, String deviceType, String deviceStatus) throws DeviceManagementException { try { DeviceManagementDAOFactory.openConnection(); return deviceDAO.getDeviceCount(deviceType, deviceStatus, tenantId); @@ -3054,8 +3053,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List getDeviceIdentifiersByStatus(String deviceType, String deviceStatus) throws DeviceManagementException { - int tenantId = this.getTenantId(); + public List getDeviceIdentifiersByStatus(int tenantId, String deviceType, String deviceStatus) throws DeviceManagementException { List deviceIds; try { DeviceManagementDAOFactory.openConnection(); @@ -3075,8 +3073,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public boolean bulkUpdateDeviceStatus(String deviceType, List deviceList, String status) throws DeviceManagementException { - int tenantId = this.getTenantId(); + public boolean bulkUpdateDeviceStatus(int tenantId, String deviceType, + List deviceList, String status) + throws DeviceManagementException { boolean success; try { DeviceManagementDAOFactory.openConnection(); From 5e1945588206ea766615780dec6bc456945fd923 Mon Sep 17 00:00:00 2001 From: milanperera Date: Wed, 25 Sep 2019 16:25:38 +0200 Subject: [PATCH 02/10] Fix for entgra/product-iots#141 --- ...ApiApplicationRegistrationServiceImpl.java | 21 ++++++++++++-- .../api/util/RegistrationProfile.java | 20 +++++++++++++ .../APIManagementProviderService.java | 23 +++++++++++++++ .../APIManagementProviderServiceImpl.java | 29 +++++++++++++++---- .../client/IntegrationClientServiceImpl.java | 6 ++++ .../client/OAuthRequestInterceptor.java | 22 ++++++++++---- 6 files changed, 108 insertions(+), 13 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java index 4656653988..2beaff52ab 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -28,6 +28,8 @@ import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; +import org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor; +import org.wso2.carbon.apimgt.integration.client.store.StoreClient; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; @@ -96,9 +98,8 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi return Response.status(Response.Status.NOT_ACCEPTABLE).entity("APIs(Tags) are not allowed to this user." ).build(); } - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext. - getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName()); String username = APIUtil.getAuthenticatedUser(); + APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); String validityPeriod; if (registrationProfile.getValidityPeriod() == null) { @@ -108,6 +109,22 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi } String applicationName = registrationProfile.getApplicationName(); + + if (username.equals(registrationProfile.getUsername())) { + synchronized (ApiApplicationRegistrationServiceImpl.class) { + StoreClient storeClient = new StoreClient(new OAuthRequestInterceptor(registrationProfile.getUsername(), + registrationProfile.getPassword())); + ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( + applicationName, registrationProfile.getTags(), + ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, + registrationProfile.isAllowedToAllDomains(), validityPeriod, storeClient); + return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); + } + } + + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext. + getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName()); + synchronized (ApiApplicationRegistrationServiceImpl.class) { ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, registrationProfile.getTags(), diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java index 44cc5554fc..5c7d945c79 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java @@ -32,6 +32,10 @@ import javax.xml.bind.annotation.XmlRootElement; public class RegistrationProfile { @XmlElement(required = true) private String applicationName; + @XmlElement + private String username; + @XmlElement + private String password; @XmlElement(required = true) private String tags[]; @XmlElement(required = true) @@ -70,4 +74,20 @@ public class RegistrationProfile { public void setValidityPeriod(String validityPeriod) { this.validityPeriod = validityPeriod; } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java index 611679e512..4f10bedb36 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java @@ -20,6 +20,7 @@ package org.wso2.carbon.apimgt.application.extension; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; +import org.wso2.carbon.apimgt.integration.client.store.StoreClient; /** * This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM. @@ -49,6 +50,28 @@ public interface APIManagementProviderService { String keyType, String username, boolean isAllowedAllDomains, String validityTime) throws APIManagerException; + /** + * Generate and retreive application keys. if the application does exist then + * create it and subscribe to apis that are grouped with the tags. + * + * @param apiApplicationName name of the application. + * @param tags tags of the apis that application needs to be subscribed. + * @param keyType of the application. + * @param username to whom the application is created + * @param isAllowedAllDomains application is allowed to all the tenants + * @param validityTime validity period of the application + * @param storeClient Specified store client + * @return consumerkey and secrete of the created application. + * @throws APIManagerException + */ + ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, + String tags[], + String keyType, + String username, + boolean isAllowedAllDomains, + String validityTime, + StoreClient storeClient) throws APIManagerException; + /** * Remove APIM Application. */ diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java index aaa3cb87c1..d966234eba 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -94,11 +94,18 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe @Override public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], String keyType, String username, - boolean isAllowedAllDomains, String validityTime) - throws APIManagerException { - StoreClient storeClient = - APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() - .getStoreClient(); + boolean isAllowedAllDomains, String validityTime, + StoreClient sClient) throws APIManagerException { + + StoreClient storeClient; + + if (sClient == null) { + storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() + .getStoreClient(); + } else { + storeClient = sClient; + } + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext() .getTenantDomain(); try { @@ -211,4 +218,16 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } } + /** + * {@inheritDoc} + */ + @Override + public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], + String keyType, String username, + boolean isAllowedAllDomains, + String validityTime) + throws APIManagerException { + return this.generateAndRetrieveApplicationKeys(applicationName, tags, keyType, username, + isAllowedAllDomains, validityTime, null); + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java index 6341dc7a22..66c519733e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java @@ -36,6 +36,12 @@ public class IntegrationClientServiceImpl implements IntegrationClientService { publisherClient = new PublisherClient(oAuthRequestInterceptor); } + public IntegrationClientServiceImpl(OAuthRequestInterceptor oAuthRequestInterceptor) { + this.oAuthRequestInterceptor = oAuthRequestInterceptor; + storeClient = new StoreClient(oAuthRequestInterceptor); + publisherClient = new PublisherClient(oAuthRequestInterceptor); + } + public static IntegrationClientServiceImpl getInstance() { if (instance == null) { synchronized (IntegrationClientService.class) { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java index 4bf2875509..0d6d305bc7 100755 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java @@ -56,7 +56,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private static final String APIM_SUBSCRIBE_SCOPE = "apim:subscribe"; private static final long DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS = 100000; private DCRClient dcrClient; - private static OAuthApplication oAuthApplication; + private OAuthApplication oAuthApplication; private static Map tenantUserTokenMap = new ConcurrentHashMap<>(); private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class); @@ -67,8 +67,15 @@ public class OAuthRequestInterceptor implements RequestInterceptor { String username = APIMConfigReader.getInstance().getConfig().getUsername(); String password = APIMConfigReader.getInstance().getConfig().getPassword(); dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger()) - .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, - password)) + .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) + .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) + .target(DCRClient.class, Utils.replaceProperties( + APIMConfigReader.getInstance().getConfig().getDcrEndpoint())); + } + + public OAuthRequestInterceptor(String username, String password) { + dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger()) + .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(DCRClient.class, Utils.replaceProperties( APIMConfigReader.getInstance().getConfig().getDcrEndpoint())); @@ -82,7 +89,11 @@ public class OAuthRequestInterceptor implements RequestInterceptor { clientProfile.setClientName(APPLICATION_NAME); clientProfile.setCallbackUrl(""); clientProfile.setGrantType(GRANT_TYPES); - clientProfile.setOwner(APIMConfigReader.getInstance().getConfig().getUsername()); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + if (username == null || username.isEmpty()) { + username = APIMConfigReader.getInstance().getConfig().getUsername(); + } + clientProfile.setOwner(username); clientProfile.setSaasApp(true); oAuthApplication = dcrClient.register(clientProfile); } @@ -100,8 +111,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { JWTClient jwtClient = APIIntegrationClientDataHolder.getInstance().getJwtClientManagerService() .getJWTClient(); tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(), - oAuthApplication.getClientSecret(), username, - REQUIRED_SCOPE); + oAuthApplication.getClientSecret(), username, REQUIRED_SCOPE); tenantBasedAccessTokenInfo.setExpiresIn( System.currentTimeMillis() + (tenantBasedAccessTokenInfo.getExpiresIn() * 1000)); if (tenantBasedAccessTokenInfo.getScopes() == null) { From 8b61bbabeab7d2417107dc276d93baebd17658d1 Mon Sep 17 00:00:00 2001 From: Vinojini Paramasivam Date: Thu, 26 Sep 2019 04:11:55 +0000 Subject: [PATCH 03/10] Change search by group name to case insensitive --- .../service/impl/admin/GroupManagementAdminServiceImpl.java | 4 ++-- .../device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 0668b30c4e..5c0537d2d3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -40,8 +40,8 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ try { RequestValidationUtil.validatePaginationParameters(offset, limit); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); - request.setGroupName(name); - request.setOwner(owner); + request.setGroupName(name.toUpperCase()); + request.setOwner(owner.toUpperCase()); PaginationResult deviceGroupsResult = DeviceMgtAPIUtils.getGroupManagementProviderService() .getGroups(request); DeviceGroupList deviceGroupList = new DeviceGroupList(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java index 584a4f9a45..8ef981e701 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java @@ -55,11 +55,11 @@ public class GenericGroupDAOImpl extends AbstractGroupDAOImpl { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?"; if (groupName != null && !groupName.isEmpty()) { - sql += " AND GROUP_NAME LIKE ?"; + sql += " AND UPPER(GROUP_NAME) LIKE ?"; hasGroupName = true; } if (owner != null && !owner.isEmpty()) { - sql += " AND OWNER LIKE ?"; + sql += " AND UPPER(OWNER) LIKE ?"; hasOwner = true; } if (hasLimit) { From cc2eccae5d9a33b1d17e52a4f963adf94ba57e6a Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 26 Sep 2019 22:38:45 +0530 Subject: [PATCH 04/10] Fix configuration retrieval issue with non default admin credentials --- .../impl/DeviceManagementConfigServiceImpl.java | 17 ++++++++++------- .../mgt/core/DeviceManagementConstants.java | 2 -- .../device/mgt/core/util/DeviceManagerUtil.java | 6 +++--- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java index 93aba13627..6fac3b8d8d 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java @@ -35,6 +35,9 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; +import org.wso2.carbon.device.mgt.core.config.keymanager.KeyManagerConfigurations; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; @@ -163,13 +166,13 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig private void setAccessTokenToDeviceConfigurations(DeviceConfiguration devicesConfiguration) throws DeviceManagementException { try { - AppRegistrationCredentials credentials = - DeviceManagerUtil.getApplicationRegistrationCredentials( - System.getProperty(DeviceManagementConstants - .ConfigurationManagement.IOT_GATEWAY_HOST), - System.getProperty(DeviceManagementConstants - .ConfigurationManagement.IOT_GATEWAY_HTTPS_PORT), - DeviceManagementConstants.ConfigurationManagement.ADMIN_CREDENTIALS); + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + KeyManagerConfigurations kmConfig = deviceManagementConfig.getKeyManagerConfigurations(); + AppRegistrationCredentials credentials = DeviceManagerUtil.getApplicationRegistrationCredentials( + System.getProperty(DeviceManagementConstants.ConfigurationManagement.IOT_GATEWAY_HOST), + System.getProperty(DeviceManagementConstants.ConfigurationManagement.IOT_GATEWAY_HTTPS_PORT), + kmConfig.getAdminUsername(), + kmConfig.getAdminPassword()); AccessTokenInfo accessTokenForAdmin = DeviceManagerUtil.getAccessTokenForDeviceOwner( DeviceManagementConstants.ConfigurationManagement.SCOPES_FOR_TOKEN, credentials.getClient_id(), credentials.getClient_secret(), diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index 7c7f265353..9046c5c600 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -31,11 +31,9 @@ public final class DeviceManagementConstants { private ConfigurationManagement(){ throw new AssertionError(); } - public static final String ADMIN_CREDENTIALS = "admin:admin"; public static final String SCOPES_FOR_TOKEN = "perm:device:operations perm:device:publish-event"; public static final String IOT_GATEWAY_HOST = "iot.gateway.host"; public static final String IOT_GATEWAY_HTTPS_PORT = "iot.gateway.https.port"; - public static final String MQTT_ENDPOINTS = "mqttEndpoints"; public static final String APPLICATION_REGISTRATION_API_ENDPOINT = "/api-application-registration/register"; public static final String AUTHORIZATION_HEADER = "authorization"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index 6ceb93ba46..1890d399cd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -606,7 +606,7 @@ public final class DeviceManagerUtil { */ @SuppressWarnings("PackageAccessibility") public static AppRegistrationCredentials getApplicationRegistrationCredentials(String host, String port, - String credentials) + String username, String password) throws ApplicationRegistrationException { if (host == null || port == null) { String msg = "Required gatewayHost or gatewayPort system property is null"; @@ -621,8 +621,8 @@ public final class DeviceManagerUtil { apiEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); apiEndpoint.setHeader(DeviceManagementConstants.ConfigurationManagement.AUTHORIZATION_HEADER, - DeviceManagementConstants.ConfigurationManagement.BASIC_AUTH.concat(" ") - .concat(getBase64EncodedCredentials(credentials))); + DeviceManagementConstants.ConfigurationManagement.BASIC_AUTH.concat(" ") + .concat(getBase64EncodedCredentials(username + ":" + password))); apiEndpoint.setEntity(constructApplicationRegistrationPayload()); HttpResponse response = client.execute(apiEndpoint); if (response != null) { From a716d280463d8a17e34c44a80ae9d8ed75b0b304 Mon Sep 17 00:00:00 2001 From: milanperera Date: Thu, 26 Sep 2019 22:33:26 +0200 Subject: [PATCH 05/10] Fix build failure --- .../carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java index f5f3867653..5a65c3f9b5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java @@ -54,7 +54,7 @@ public class APIPublisherServiceTest extends BaseAPIPublisherTest { @BeforeTest public void initialConfigs() throws Exception { - initializeOAuthApplication(); + //initializeOAuthApplication(); WebappPublisherConfig.init(); } From 3dcf19dffa1ea047b7baa1c54a7dc8f4b6b56ed8 Mon Sep 17 00:00:00 2001 From: Vinojini Paramasivam Date: Fri, 27 Sep 2019 05:51:59 +0000 Subject: [PATCH 06/10] Show the applied policies when click view button on policy compliance --- .../cdmf.page.effective-policy.view/view.hbs | 1 + .../public/js/view.js | 21 ++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.effective-policy.view/view.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.effective-policy.view/view.hbs index 4fbf555f53..c8c9b5e23c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.effective-policy.view/view.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.effective-policy.view/view.hbs @@ -40,4 +40,5 @@ {{#zone "content"}} {{unit "cdmf.unit.device.operation-mod"}} {{unit "cdmf.unit.effective-policy.view"}} + {{unit "cdmf.unit.lib.data-table"}} {{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.effective-policy.view/public/js/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.effective-policy.view/public/js/view.js index a2b2e27b94..acc427d16f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.effective-policy.view/public/js/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.effective-policy.view/public/js/view.js @@ -76,25 +76,26 @@ var displayPolicy = function (policyPayloadObj) { var policyOperationsStylesSrc = context + '/public/cdmf.unit.device.type.' + deviceType + '.policy-view/css/' + deviceType + '-policy-view.css'; var policyOperationsTemplateCacheKey = deviceType + '-policy-operations'; - - $.isResourceExists(policyOperationsTemplateSrc, function (status) { + + if (policyOperationsTemplateSrc) { + if (policyOperationsScriptSrc) { + var script = document.createElement('script'); + script.type = 'text/javascript'; + script.src = policyOperationsScriptSrc; + $(".wr-advance-operations").prepend(script); + } $.template(policyOperationsTemplateCacheKey, policyOperationsTemplateSrc, function (template) { var content = template(); $("#device-type-policy-operations").html(content).removeClass("hidden"); $(".policy-platform").addClass("hidden"); - $.isResourceExists(policyOperationsScriptSrc, function (status) { - var script = document.createElement('script'); - script.type = 'text/javascript'; - script.src = policyOperationsScriptSrc; - $(".wr-advance-operations").prepend(script); + if (policyOperationsScriptSrc) { /* This method should be implemented in the relevant plugin side and should include the logic to populate the policy profile in the plugin specific UI. */ polulateProfileOperations(policyPayloadObj["profile"]["profileFeaturesList"]); - }); + } }); - $.isResourceExists(policyOperationsStylesSrc, function (status) { var style = document.createElement('link'); style.type = 'text/css'; @@ -104,7 +105,7 @@ var displayPolicy = function (policyPayloadObj) { }); $(".wr-advance-operations-init").addClass("hidden"); - }); + } }; /** From 2c27830eccac3306e5a357a6a6e05a7b309b263a Mon Sep 17 00:00:00 2001 From: ausamriyaaz Date: Fri, 27 Sep 2019 15:42:01 +0530 Subject: [PATCH 07/10] Fix Null pointer exception --- .../impl/admin/GroupManagementAdminServiceImpl.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 5c0537d2d3..f1783cb619 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -40,8 +40,12 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ try { RequestValidationUtil.validatePaginationParameters(offset, limit); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); - request.setGroupName(name.toUpperCase()); - request.setOwner(owner.toUpperCase()); + if (name != null){ + request.setGroupName(name.toUpperCase()); + } + if (owner != null) { + request.setOwner(owner.toUpperCase()); + } PaginationResult deviceGroupsResult = DeviceMgtAPIUtils.getGroupManagementProviderService() .getGroups(request); DeviceGroupList deviceGroupList = new DeviceGroupList(); From f28d42d7ce9bd69945daff52ca6557aabf05ccc6 Mon Sep 17 00:00:00 2001 From: Turcy Date: Mon, 30 Sep 2019 11:30:09 +0530 Subject: [PATCH 08/10] Fix device-type features edit issue --- .../pages/cdmf.page.devicetype.edit/edit.hbs | 21 ++++--- .../public/js/bottomJs.js | 62 ++++++++++++------- 2 files changed, 52 insertions(+), 31 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs index 599ffcec4e..1203de1aea 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.hbs @@ -98,14 +98,15 @@
- +
- +
- +
@@ -115,16 +116,16 @@
- +
- +
- + class="form-control feature-description" rows="1" cols="30">
@@ -221,7 +222,7 @@

- + @@ -268,4 +269,4 @@ {{#zone "bottomJs"}} {{js "js/bottomJs.js"}} -{{/zone}} \ No newline at end of file +{{/zone}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js index 320d630efe..d5bd168f87 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/public/js/bottomJs.js @@ -123,27 +123,28 @@ $(document).ready(function () { var addFeatureButton = $('.add_feature_button'); //Add button selector var featureWrapper = $('.feature_field_wrapper'); //Input field wrapper $(addFeatureButton).click(function(){ //Once add button is clicked - var featureFieldHtml = '
' + - '
' + - '
' + - '
' + var featureFieldHtml = '
' + + '
' + + '
' + + '
' + + '
'; $(featureWrapper).append(featureFieldHtml); // Add field html }); $(featureWrapper).on('click', '.remove_feature_button', function(e){ //Once remove button is clicked e.preventDefault(); $(this).parent('div').remove(); //Remove field html - op--; //Decrement field counter }); /** * Following click function would execute * when a user clicks on "Add Device type" button. */ - $("button#add-devicetype-btn").click(function () { + $("button#edit-devicetype-btn").click(function () { var errorMsgWrapper = "#devicetype-create-error-msg"; var errorMsg = "#devicetype-create-error-msg span"; @@ -155,13 +156,19 @@ $(document).ready(function () { if (!deviceTypeName || deviceTypeName.trim() == "" ) { $(errorMsg).text("Device Type Name Cannot be empty."); $(errorMsgWrapper).removeClass("hidden"); + $([document.documentElement, document.body]).animate({ + scrollTop: $(".page-sub-title").offset().top + }, 500); return; } - if (!deviceTypeDescription || deviceTypeDescription.trim() == "" ) { + if (!deviceTypeDescription || deviceTypeDescription.trim() == "") { $(errorMsg).text("Device Type Description Cannot be empty."); $(errorMsgWrapper).removeClass("hidden"); - return + $([document.documentElement, document.body]).animate({ + scrollTop: $(".page-sub-title").offset().top + }, 500); + return; } deviceType.name = deviceTypeName.trim(); @@ -197,17 +204,29 @@ $(document).ready(function () { } var features = []; + var featureCodesValidation = true; + var regexp = /^[a-zA-Z0-9-_]+$/; $('div[name^="deviceFeature"]').each(function() { - var featureName = $(this).find("#feature-name").val(); - var featureCode = $(this).find("#feature-code").val(); - if (featureName && featureName.trim() != "" && featureCode && featureCode.trim() != "") { - var feature = {}; - feature.name = featureName.trim(); - feature.code = featureCode.trim(); - feature.description = $("#feature-description").val(); - features.push(feature); - } + var featureName = $(this).find(".feature-name").val(); + var featureCode = $(this).find(".feature-code").val(); + var featureDescription = $(this).find(".feature-description").val(); + if (featureName && featureName.trim() != "" && featureCode && featureCode.trim() != "") { + featureCodesValidation = featureCodesValidation && (featureCode.search(regexp) != -1); + var feature = {}; + feature.name = featureName.trim(); + feature.code = featureCode.trim(); + feature.description = featureDescription; + features.push(feature); + } }); + if (!featureCodesValidation) { + $(errorMsg).text("Device Type feature code can only contain alphanumeric, underscore and dash characters."); + $(errorMsgWrapper).removeClass("hidden"); + $([document.documentElement, document.body]).animate({ + scrollTop: $(".page-sub-title").offset().top + }, 500); + return; + } deviceType.deviceTypeMetaDefinition.features = features; var addRoleAPI = apiBasePath + "/admin/device-types/" + deviceType.name; @@ -217,6 +236,7 @@ $(document).ready(function () { deviceType, function (data, textStatus, jqXHR) { if (jqXHR.status == 200) { + $(errorMsgIdentifier).addClass(" hidden"); $("#modalDevice").modal('show'); } }, @@ -234,4 +254,4 @@ $(document).ready(function () { ); }); -}); \ No newline at end of file +}); From a044bbd385dea33a2b673a73b460c73f80db27a0 Mon Sep 17 00:00:00 2001 From: milanperera Date: Mon, 30 Sep 2019 15:44:54 +0200 Subject: [PATCH 09/10] fix entgra/product-iots#172 --- .../impl/UserManagementServiceImpl.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 090563af7b..791751eb41 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -115,6 +115,7 @@ public class UserManagementServiceImpl implements UserManagementService { private static final Log log = LogFactory.getLog(UserManagementServiceImpl.class); private static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user"; + private static final String DEFAULT_SUBSCRIBER = "Internal/subscriber"; // Permissions that are given for a normal device user. private static final Permission[] PERMISSIONS_FOR_DEVICE_USER = { @@ -159,6 +160,23 @@ public class UserManagementServiceImpl implements UserManagementService { String[] userInfoRoles = userInfo.getRoles(); tmpRoles.add(DEFAULT_DEVICE_USER); if (userInfoRoles != null) { + //check if subscriber role is coming in the payload + boolean subscriberFound = false; + for (String r : userInfoRoles) { + if (DEFAULT_SUBSCRIBER.equals(r)) { + subscriberFound = true; + break; + } + } + if (!subscriberFound) { + // Add Internal/subscriber role to new users + if (userStoreManager.isExistingRole(DEFAULT_SUBSCRIBER)) { + tmpRoles.add(DEFAULT_SUBSCRIBER); + } else { + log.warn("User: " + userInfo.getUsername() + " will not be able to enroll devices as '" + + DEFAULT_SUBSCRIBER + "' is missing in the system"); + } + } tmpRoles.addAll(Arrays.asList(userInfoRoles)); } String[] roles = new String[tmpRoles.size()]; From 576ccd2363e54a9d19d71d5ae8cb8f5c8ff8b222 Mon Sep 17 00:00:00 2001 From: milanperera Date: Mon, 30 Sep 2019 15:54:12 +0200 Subject: [PATCH 10/10] Fix issues in fix-172 --- .../impl/UserManagementServiceImpl.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 791751eb41..11260d9fb3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -159,26 +159,31 @@ public class UserManagementServiceImpl implements UserManagementService { List tmpRoles = new ArrayList<>(); String[] userInfoRoles = userInfo.getRoles(); tmpRoles.add(DEFAULT_DEVICE_USER); + + boolean subscriberFound = false; + if (userInfoRoles != null) { + //check if subscriber role is coming in the payload - boolean subscriberFound = false; for (String r : userInfoRoles) { if (DEFAULT_SUBSCRIBER.equals(r)) { subscriberFound = true; break; } } - if (!subscriberFound) { - // Add Internal/subscriber role to new users - if (userStoreManager.isExistingRole(DEFAULT_SUBSCRIBER)) { - tmpRoles.add(DEFAULT_SUBSCRIBER); - } else { - log.warn("User: " + userInfo.getUsername() + " will not be able to enroll devices as '" + - DEFAULT_SUBSCRIBER + "' is missing in the system"); - } - } tmpRoles.addAll(Arrays.asList(userInfoRoles)); } + + if (!subscriberFound) { + // Add Internal/subscriber role to new users + if (userStoreManager.isExistingRole(DEFAULT_SUBSCRIBER)) { + tmpRoles.add(DEFAULT_SUBSCRIBER); + } else { + log.warn("User: " + userInfo.getUsername() + " will not be able to enroll devices as '" + + DEFAULT_SUBSCRIBER + "' is missing in the system"); + } + } + String[] roles = new String[tmpRoles.size()]; tmpRoles.toArray(roles);