diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java index 8bad3de1a8..06d344a514 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java @@ -55,7 +55,7 @@ public class AuthenticationHandler extends AbstractHandler { private static final String X_JWT_ASSERTION = "X-JWT-Assertion"; private static final String JWTTOKEN = "JWTToken"; private static final String AUTHORIZATION = "Authorization"; - private static final String BEARER = "Bearer "; + private static final String BEARER = "Basic "; private static final String CONTENT_TYPE = "Content-Type"; private IOTServerConfiguration iotServerConfiguration; @@ -95,7 +95,7 @@ public class AuthenticationHandler extends AbstractHandler { log.debug("Verify Cert:\n" + mdmSignature); } URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + "ios"); - Map certVerifyHeaders = this.setHeaders(this.restInvoker); + Map certVerifyHeaders = this.setHeaders(); Certificate certificate = new Certificate(); certificate.setPem(mdmSignature); @@ -127,7 +127,7 @@ public class AuthenticationHandler extends AbstractHandler { String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(this.restInvoker); + Map certVerifyHeaders = this.setHeaders(); Certificate certificate = new Certificate(); certificate.setPem(subjectDN); certificate.setTenantId(tenantId); @@ -157,7 +157,7 @@ public class AuthenticationHandler extends AbstractHandler { } String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(this.restInvoker); + Map certVerifyHeaders = this.setHeaders(); Certificate certificate = new Certificate(); certificate.setPem(encodedPem); @@ -184,9 +184,6 @@ public class AuthenticationHandler extends AbstractHandler { } catch (URISyntaxException e) { log.error("Error while processing certificate.", e); return false; - } catch (APIMCertificateMGTException e) { - log.error("Error while processing certificate.", e); - return false; } catch (CertificateException e) { log.error("Certificate issue occurred when generating converting PEM to x509Certificate", e); return false; @@ -212,9 +209,9 @@ public class AuthenticationHandler extends AbstractHandler { return null; } - private Map setHeaders(RESTInvoker restInvoker) throws APIMCertificateMGTException { + private Map setHeaders() { Map map = new HashMap<>(); - String accessToken = Utils.getAccessToken(iotServerConfiguration, restInvoker); + String accessToken = Utils.getBase64EncodedToken(iotServerConfiguration); map.put(AUTHORIZATION, BEARER + accessToken); map.put(CONTENT_TYPE, "application/json"); return map; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java index f149868e76..5be2c18705 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java @@ -135,38 +135,14 @@ public class Utils { } /** - * This class get the access token from the key manager. + * This method is used to get the base64 encoded token. * * @param iotServerConfiguration Instance of the IoTsererConfiguration. * @return Access token will be returned. - * @throws APIMCertificateMGTException */ - public static String getAccessToken(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker) - throws APIMCertificateMGTException { - try { - if (clientId == null || clientSecret == null) { - getClientSecretes(iotServerConfiguration, restInvoker); - } - URI tokenUrl = new URI(iotServerConfiguration.getOauthTokenEndpoint()); - String tokenContent = "grant_type=password&username=" + iotServerConfiguration.getUsername() + "&password=" + - iotServerConfiguration.getPassword() + "&scope=activity-view"; - String tokenBasicAuth = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes()); - Map tokenHeaders = new HashMap<>(); - tokenHeaders.put("Authorization", tokenBasicAuth); - tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded"); - - RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, tokenContent); - if (log.isDebugEnabled()) { - log.debug("Token response:" + response.getContent()); - } - JSONObject jsonResponse = new JSONObject(response.getContent()); - return jsonResponse.getString("access_token"); - - } catch (URISyntaxException | IOException e) { - throw new APIMCertificateMGTException("Error occurred while trying to call oauth token endpoint", e); - } catch (JSONException e) { - throw new APIMCertificateMGTException("Error occurred while converting the json to object", e); - } + public static String getBase64EncodedToken(IOTServerConfiguration iotServerConfiguration) { + return Base64.encode((iotServerConfiguration.getUsername() + ":" + iotServerConfiguration.getPassword()). + getBytes()); } /** diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java index b3b8cdac78..23e6b251fc 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java @@ -92,8 +92,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest { HashMap transportHeaders = new HashMap<>(); transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); setMockClient(); - this.mockClient.setResponse(getDCRResponse()); - this.mockClient.setResponse(getAccessTokenReponse()); this.mockClient.setResponse(getValidationResponse()); boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, transportHeaders, "https://test.com/testservice/device-mgt/testdevice")); @@ -107,7 +105,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest { HashMap transportHeaders = new HashMap<>(); transportHeaders.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, "Test Header"); setMockClient(); - this.mockClient.setResponse(getAccessTokenReponse()); this.mockClient.setResponse(getValidationResponse()); boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, transportHeaders, "https://test.com/testservice/device-mgt/testdevice")); @@ -121,7 +118,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest { HashMap transportHeaders = new HashMap<>(); transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header"); setMockClient(); - this.mockClient.setResponse(getAccessTokenReponse()); this.mockClient.setResponse(getValidationResponse()); MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); @@ -141,7 +137,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest { HashMap transportHeaders = new HashMap<>(); transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); setMockClient(); - this.mockClient.setResponse(getAccessTokenReponse()); this.mockClient.setResponse(getValidationResponse()); MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); @@ -156,7 +151,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest { HashMap transportHeaders = new HashMap<>(); transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); setMockClient(); - this.mockClient.setResponse(getAccessTokenReponse()); this.mockClient.setResponse(getInvalidResponse()); MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); @@ -185,7 +179,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest { HashMap transportHeaders = new HashMap<>(); transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); setMockClient(); - this.mockClient.setResponse(getAccessTokenReponse()); this.mockClient.setResponse(null); MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/WEB-INF/web.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/WEB-INF/web.xml index 6fd45f33b3..9722ee843e 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/WEB-INF/web.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/WEB-INF/web.xml @@ -37,6 +37,10 @@ doAuthentication true + + basicAuth + true + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index 71ce11b6b1..b25837154f 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -324,9 +324,14 @@ public class CertificateGenerator { KeyStoreReader keyStoreReader = new KeyStoreReader(); if (distinguishedName != null && !distinguishedName.isEmpty()) { if (distinguishedName.contains("/CN=")) { - String[] dnSplits = distinguishedName.split("/CN="); - String commonNameExtracted = dnSplits[dnSplits.length - 1]; - lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted); + String[] dnSplits = distinguishedName.split("/"); + for (String dnPart : dnSplits) { + if (dnPart.contains("CN=")) { + String commonNameExtracted = dnPart.replace("CN=", ""); + lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted); + break; + } + } } else { LdapName ldapName; try { @@ -711,4 +716,4 @@ public class CertificateGenerator { return generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName()); } -} \ No newline at end of file +} 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 4cf332c0b8..aba6d9819c 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 @@ -901,12 +901,7 @@ public interface DeviceManagementService { required = true) @PathParam("device-id") @Size(max = 45) - String deviceId, - @ApiParam( - name = "permanentDelete", - value = "Boolean flag indicating whether to permanently delete the device.", - required = false) - @QueryParam("permanentDelete") boolean permanentDelete); + String deviceId); @GET @Path("/{type}/{id}/features") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java index b96977adfb..4377c9d185 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java @@ -15,6 +15,22 @@ * specific language governing permissions and limitations * under the License. * + * + * Copyright (c) 2019, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; @@ -76,6 +92,12 @@ import java.util.List; description = "Update the ownership of the device", key = "perm:admin:devices:update-enrollment", permissions = {"/device-mgt/admin/devices/update-enrollment"} + ), + @Scope( + name = "Permanently Delete the device specified by device id", + description = "Permanently Delete the device specified by device id", + key = "perm:devices:permanent-delete", + permissions = {"/device-mgt/admin/devices/permanent-delete"} ) } ) @@ -225,4 +247,72 @@ public interface DeviceManagementAdminService { value = "List of device identifiers.", required = true) List deviceIdentifiers); + + @DELETE + @Path("/type/{device-type}/id/{device-id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + consumes = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Permanently remove the Device Specified by the Device ID", + notes = "Returns the status of the permanently deleted device operation and the details of the deleted device.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:permanent-delete") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully deleted the device permanently.", + response = Device.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "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."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest " + + "version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) + }) + Response deleteDevicePermanently( + @ApiParam( + name = "device-type", + value = "The device type, such as ios, android, or windows.", + required = true) + @PathParam("device-type") + @Size(max = 45) + String deviceType, + @ApiParam( + name = "device-id", + value = "The device identifier of the device.", + required = true) + @PathParam("device-id") + @Size(max = 45) + String deviceId); } 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 d87bfcd19a..9febec7ec3 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 @@ -105,7 +105,6 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Map; @Path("/devices") @Produces(MediaType.APPLICATION_JSON) @@ -326,8 +325,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Override @Path("/type/{device-type}/id/{device-id}") public Response deleteDevice(@PathParam("device-type") String deviceType, - @PathParam("device-id") String deviceId, - @QueryParam("permanentDelete") boolean permanentDelete) { + @PathParam("device-id") String deviceId) { DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { @@ -336,16 +334,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { if (persistedDevice == null) { return Response.status(Response.Status.NOT_FOUND).build(); } - - boolean response; - - if (permanentDelete) { - response = deviceManagementProviderService.deleteDevice(deviceIdentifier); - } else { - response = deviceManagementProviderService.disenrollDevice(deviceIdentifier); - } + boolean response = deviceManagementProviderService.disenrollDevice(deviceIdentifier); return Response.status(Response.Status.OK).entity(response).build(); - } catch (DeviceManagementException e) { String msg = "Error encountered while deleting device of type : " + deviceType + " and " + "ID : " + deviceId; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index a7ef07324e..031fd1c56a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -15,6 +15,22 @@ * specific language governing permissions and limitations * under the License. * + * + * Copyright (c) 2019, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; @@ -24,10 +40,12 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; @@ -117,4 +135,32 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } + + @DELETE + @Override + @Path("/type/{device-type}/id/{device-id}") + public Response deleteDevicePermanently(@PathParam("device-type") String deviceType, + @PathParam("device-id") String deviceId) { + DeviceManagementProviderService deviceManagementProviderService = + DeviceMgtAPIUtils.getDeviceManagementService(); + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); + Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, true); + if (persistedDevice == null) { + String msg = "No device found with the device type: " + deviceType + + " having the device ID: " + deviceId + " to permanently delete."; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + boolean response = deviceManagementProviderService.deleteDevice(deviceIdentifier); + return Response.status(Response.Status.OK).entity(response).build(); + } catch (DeviceManagementException e) { + String msg = "Error encountered while permanently deleting device of type : " + deviceType + " and " + + "ID : " + deviceId; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java index bdf1662687..edae86a311 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java @@ -140,7 +140,8 @@ public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagemen @Override @PUT - public Response updateDeviceType(String type, DeviceType deviceType) { + @Path("/{type}") + public Response updateDeviceType(@PathParam("type") String type, DeviceType deviceType) { if (deviceType != null && deviceType.getDeviceTypeMetaDefinition() != null) { if (deviceType.getName() == null || !deviceType.getName().equals(type)) { return Response.status(Response.Status.BAD_REQUEST).entity("Type name mismatch. Expected: '" + type + @@ -166,7 +167,10 @@ public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagemen } @Override - public Response addDeviceTypePlatformConfig(String type, PlatformConfiguration platformConfiguration) { + @POST + @Path("/{type}/configs") + public Response addDeviceTypePlatformConfig(@PathParam("type") String type, + PlatformConfiguration platformConfiguration) { boolean isSaved; if (platformConfiguration.getType() == null || !platformConfiguration.getType().equals(type)) { return Response.status(Response.Status.BAD_REQUEST).entity("Type name mismatch. Expected: '" + type + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index b5bb8ce975..57f71d18a6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -481,8 +481,7 @@ public class DeviceManagementServiceImplTest { public void testDeleteDevice() { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString() - , false); + Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -492,8 +491,7 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceManagementProviderService); Mockito.when(this.deviceManagementProviderService .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean())).thenReturn(null); - Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString() - , false); + Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); } @@ -504,8 +502,7 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceManagementProviderService); Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any(DeviceIdentifier.class))) .thenThrow(new DeviceManagementException()); - Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString() - , false); + Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 6674c37a77..f62d915d1b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -277,6 +277,17 @@ public interface DeviceDAO { */ List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + + /** + * This method is used to search for devices within a specific group. + * + * @param request PaginationRequest object holding the data for pagination + * @param tenantId tenant id. + * @return returns paginated list of devices. + * @throws DeviceManagementDAOException + */ + List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to retrieve all the devices of a given tenant and device type. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 872ea7c285..8f38bc9d73 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -153,6 +153,137 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + + @Override + public List searchDevicesInGroup(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + + int groupId = request.getGroupId(); + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + + try { + conn = this.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + + " d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; + + + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") gd, DM_DEVICE_TYPE t"; + + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; + } + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + + sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " LIMIT ?,?"; + + stmt = conn.prepareStatement(sql); + + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + + int paramIdx = 3; + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, status); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving information of" + + " devices belonging to group : " + groupId, e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 33875fc9c7..2d568fed7e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -159,6 +159,137 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + @Override + public List searchDevicesInGroup(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + + int groupId = request.getGroupId(); + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + + try { + conn = this.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + + " d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; + + + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") gd, DM_DEVICE_TYPE t"; + + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; + } + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + + sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + + int paramIdx = 3; + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, status); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving information of" + + " devices belonging to group : " + groupId, e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + + @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index f8bce9b286..e46d460bcb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -140,6 +140,136 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + @Override + public List searchDevicesInGroup(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + + int groupId = request.getGroupId(); + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + + try { + conn = this.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + + " d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; + + + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") gd, DM_DEVICE_TYPE t"; + + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; + } + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + + sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(sql); + + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + + int paramIdx = 3; + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, status); + } + stmt.setInt(paramIdx, request.getRowCount()); + stmt.setInt(paramIdx++, request.getStartIndex()); + + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving information of" + + " devices belonging to group : " + groupId, e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index ee60068fa8..12635fd1a1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -156,6 +156,136 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + @Override + public List searchDevicesInGroup(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + + int groupId = request.getGroupId(); + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + + try { + conn = this.getConnection(); + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + + " d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; + + + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") gd, DM_DEVICE_TYPE t"; + + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; + } + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + + sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + + int paramIdx = 3; + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, status); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving information of" + + " devices belonging to group : " + groupId, e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { 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 cc39dff8ff..2f6d4104cb 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 @@ -827,7 +827,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } else { try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevices(request, tenantId); + if(request.getGroupId()!=0){ + allDevices = deviceDAO.searchDevicesInGroup(request, tenantId); + } else{ + allDevices = deviceDAO.getDevices(request, tenantId); + } count = deviceDAO.getDeviceCount(request, tenantId); } catch (DeviceManagementDAOException e) { String msg = "Error occurred while retrieving device list pertaining to the current tenant"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java index edcb4f76e5..5cc28bc8ec 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java @@ -34,6 +34,7 @@ */ package org.wso2.carbon.device.mgt.extensions.device.type.template; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; @@ -58,10 +59,12 @@ import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAOD import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypePluginExtensionException; import org.wso2.carbon.device.mgt.extensions.device.type.template.feature.ConfigurationBasedFeatureManager; import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypePluginConstants; import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager; +import org.wso2.carbon.device.mgt.extensions.spi.DeviceTypePluginExtensionService; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.utils.CarbonUtils; @@ -213,6 +216,35 @@ public class DeviceTypeManager implements DeviceManager { } } } + setDeviceTypePluginManager(); + } + + /** + * Set device type plugin DAO manager of each device type in a HashMap which can then be used via individual + * device type plugin in working with its DAO components + */ + private void setDeviceTypePluginManager() { + if (StringUtils.isNotEmpty(deviceType)) { + if (deviceTypePluginDAOManager != null) { + DeviceTypePluginExtensionService deviceTypeManagerExtensionService = + new DeviceTypePluginExtensionServiceImpl(); + try { + deviceTypeManagerExtensionService.addPluginDAOManager(deviceType, deviceTypePluginDAOManager); + } catch (DeviceTypePluginExtensionException e) { + String msg = "Error occurred while saving DeviceTypePluginDAOManager for device type: " + + deviceType; + log.error(msg); + throw new DeviceTypeDeployerPayloadException(msg); + } + } else { + log.warn("Could not save DeviceTypePluginDAOManager for device type: " + deviceType + + " since DeviceTypePluginDAOManager is null."); + } + } else { + String msg = "Could not save DeviceTypePluginDAOManager since device type is null or empty."; + log.error(msg); + throw new DeviceTypeDeployerPayloadException(msg); + } } @Override @@ -307,15 +339,11 @@ public class DeviceTypeManager implements DeviceManager { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); } } catch (DeviceTypeMgtPluginException e) { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); - } catch (DeviceTypeMgtPluginException ex) { - String msg = "Error occurred while roll back the device enrol transaction :" + - device.toString(); - log.warn(msg, ex); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); String msg = "Error while enrolling the " + deviceType + " device : " + device.getDeviceIdentifier(); throw new DeviceManagementException(msg, e); + } finally { + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return status; } @@ -334,16 +362,12 @@ public class DeviceTypeManager implements DeviceManager { status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(device); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); } catch (DeviceTypeMgtPluginException e) { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); - } catch (DeviceTypeMgtPluginException mobileDAOEx) { - String msg = "Error occurred while roll back the update device transaction :" + - device.toString(); - log.warn(msg, mobileDAOEx); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); String msg = "Error while updating the enrollment of the " + deviceType + " device : " + device.getDeviceIdentifier(); throw new DeviceManagementException(msg, e); + } finally { + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return status; } @@ -378,13 +402,7 @@ public class DeviceTypeManager implements DeviceManager { deviceId.getId(); throw new DeviceManagementException(msg, e); } finally { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); - } catch (DeviceTypeMgtPluginException e) { - String msg = "Error occurred while closing the transaction to check device " + - deviceId.getId() + " is enrolled."; - log.warn(msg, e); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return isEnrolled; } @@ -419,12 +437,7 @@ public class DeviceTypeManager implements DeviceManager { throw new DeviceManagementException( "Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e); } finally { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); - } catch (DeviceTypeMgtPluginException e) { - String msg = "Error occurred while closing the transaction to get device " + deviceId.getId(); - log.warn(msg, e); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return device; } @@ -447,14 +460,11 @@ public class DeviceTypeManager implements DeviceManager { status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(updatedDevice); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); } catch (DeviceTypeMgtPluginException e) { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); - } catch (DeviceTypeMgtPluginException transactionException) { - String msg = "Error occurred while rolling back transaction for device: " + deviceId.getId(); - log.warn(msg, transactionException); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); throw new DeviceManagementException( "Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e); + } finally { + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } } return status; @@ -544,15 +554,12 @@ public class DeviceTypeManager implements DeviceManager { status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(existingDevice); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); } catch (DeviceTypeMgtPluginException e) { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); - } catch (DeviceTypeMgtPluginException e1) { - log.warn("Error occurred while roll back the update device info transaction : '" + - device.toString() + "'", e1); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); throw new DeviceManagementException( "Error occurred while updating the " + deviceType + " device: '" + device.getDeviceIdentifier() + "'", e); + } finally { + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return status; } @@ -572,12 +579,7 @@ public class DeviceTypeManager implements DeviceManager { } catch (DeviceTypeMgtPluginException e) { throw new DeviceManagementException("Error occurred while fetching all " + deviceType + " devices", e); } finally { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); - } catch (DeviceTypeMgtPluginException e) { - String msg = "Error occurred while closing the transaction to get all devices."; - log.warn(msg, e); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return devices; } @@ -600,15 +602,12 @@ public class DeviceTypeManager implements DeviceManager { status = deviceTypePluginDAOManager.getDeviceDAO().deleteDevice(existingDevice); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); } catch (DeviceTypeMgtPluginException e) { - try { - deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); - } catch (DeviceTypeMgtPluginException e1) { - log.warn("Error occurred while roll back the delete device info transaction : '" + - device.toString() + "'", e1); - } + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction(); throw new DeviceManagementException( "Error occurred while deleting the " + deviceType + " device: '" + device.getDeviceIdentifier() + "'", e); + } finally { + deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection(); } return status; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java new file mode 100644 index 0000000000..e32c9e2d57 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2019, Entgra (Pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.extensions.device.type.template; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypePluginExtensionException; +import org.wso2.carbon.device.mgt.extensions.spi.DeviceTypePluginExtensionService; + +import java.util.HashMap; +import java.util.Map; + +public class DeviceTypePluginExtensionServiceImpl implements DeviceTypePluginExtensionService { + + private static final Log log = LogFactory.getLog(DeviceTypePluginExtensionServiceImpl.class); + + private static volatile Map pluginDAOManagers = new HashMap<>(); + + @Override + public void addPluginDAOManager(String deviceType, DeviceTypePluginDAOManager pluginDAOManager) + throws DeviceTypePluginExtensionException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + if (pluginDAOManager == null) { + String msg = "Cannot save DeviceTypePluginDAOManager against tenant id " + tenantId + + " and device type: " + deviceType + " since DeviceTypePluginDAOManager is null"; + log.error(msg); + throw new DeviceTypePluginExtensionException(msg); + } + if (!pluginDAOManagers.containsKey(tenantId + deviceType)) { + if (log.isDebugEnabled()) { + log.debug("Saving DeviceTypePluginDAOManager against tenant id " + tenantId + + " and device type: " + deviceType); + } + pluginDAOManagers.put(tenantId + deviceType, pluginDAOManager); + } + } + + @Override + public DeviceTypePluginDAOManager getPluginDAOManager(String deviceType) throws DeviceTypePluginExtensionException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + if (pluginDAOManagers.containsKey(tenantId + deviceType)) { + if (log.isDebugEnabled()) { + log.debug("Retrieving DeviceTypePluginDAOManager against tenant id " + tenantId + + " and device type: " + deviceType); + } + return pluginDAOManagers.get(tenantId + deviceType); + } else { + String msg = "DeviceTypePluginDAOManager could not be found against tenant id " + tenantId + + " and device type: " + deviceType; + log.error(msg); + throw new DeviceTypePluginExtensionException(msg); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java index e31149fafe..417d078868 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java @@ -1,7 +1,25 @@ +/* + * Copyright (c) 2019, Entgra (Pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.wso2.carbon.device.mgt.extensions.device.type.template.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; @@ -31,7 +49,26 @@ public class DeviceTypeDAOHandler { Context ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup(datasourceName); } catch (NamingException e) { - throw new DeviceTypeDeployerPayloadException("Error while looking up the data source: " + datasourceName, e); + String msg = "Error while looking up the data source: " + datasourceName; + log.error(msg, e); + throw new DeviceTypeDeployerPayloadException(msg, e); + } + } + + public void openConnection() throws DeviceTypeMgtPluginException { + try { + Connection conn = currentConnection.get(); + if (conn != null) { + String msg = "Database connection has already been obtained."; + log.error(msg); + throw new IllegalTransactionStateException(msg); + } + conn = dataSource.getConnection(); + currentConnection.set(conn); + } catch (SQLException e) { + String msg = "Failed to get a database connection."; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); } } @@ -41,7 +78,9 @@ public class DeviceTypeDAOHandler { conn.setAutoCommit(false); currentConnection.set(conn); } catch (SQLException e) { - throw new DeviceTypeMgtPluginException("Error occurred while retrieving datasource connection", e); + String msg = "Error occurred while retrieving datasource connection"; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); } } @@ -50,58 +89,58 @@ public class DeviceTypeDAOHandler { try { currentConnection.set(dataSource.getConnection()); } catch (SQLException e) { - throw new DeviceTypeMgtPluginException("Error occurred while retrieving data source connection", e); + String msg = "Error occurred while retrieving data source connection"; + log.error(msg, e); + throw new DeviceTypeMgtPluginException(msg, e); } } return currentConnection.get(); } - public void commitTransaction() throws DeviceTypeMgtPluginException { + public void commitTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + String msg = "No connection is associated with the current transaction. This might have ideally been " + + "caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"; + log.error(msg); + throw new IllegalStateException(msg); + } try { - Connection conn = currentConnection.get(); - if (conn != null) { - conn.commit(); - } else { - if (log.isDebugEnabled()) { - log.debug("Datasource connection associated with the current thread is null, hence commit " - + "has not been attempted"); - } - } + conn.commit(); } catch (SQLException e) { - throw new DeviceTypeMgtPluginException("Error occurred while committing the transaction", e); - } finally { - closeConnection(); + String msg = "Error occurred while committing the transaction."; + log.error(msg, e); } } - public void closeConnection() throws DeviceTypeMgtPluginException { - + public void closeConnection() { Connection con = currentConnection.get(); if (con != null) { try { con.close(); } catch (SQLException e) { - log.error("Error occurred while close the connection"); + String msg = "Error occurred while close the connection"; + log.error(msg, e); } } currentConnection.remove(); } - public void rollbackTransaction() throws DeviceTypeMgtPluginException { + public void rollbackTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + String msg = "No connection is associated with the current transaction. This might have ideally been " + + "caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"; + log.error(msg); + throw new IllegalStateException(msg); + } try { - Connection conn = currentConnection.get(); - if (conn != null) { - conn.rollback(); - } else { - if (log.isDebugEnabled()) { - log.debug("Datasource connection associated with the current thread is null, hence rollback " - + "has not been attempted"); - } - } + conn.rollback(); } catch (SQLException e) { - throw new DeviceTypeMgtPluginException("Error occurred while rollback the transaction", e); - } finally { - closeConnection(); + String msg = "Error occurred while roll-backing the transaction."; + log.error(msg, e); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypePluginExtensionException.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypePluginExtensionException.java new file mode 100644 index 0000000000..b0603f43bf --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypePluginExtensionException.java @@ -0,0 +1,12 @@ +package org.wso2.carbon.device.mgt.extensions.device.type.template.exception; + +public class DeviceTypePluginExtensionException extends Exception { + + public DeviceTypePluginExtensionException(String msg) { + super(msg); + } + + public DeviceTypePluginExtensionException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java index e29af46f12..36ae9b11dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java @@ -14,6 +14,23 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. + * + * + * Copyright (c) 2019, Entgra (Pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.extensions.internal; @@ -23,6 +40,8 @@ import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypePluginExtensionServiceImpl; +import org.wso2.carbon.device.mgt.extensions.spi.DeviceTypePluginExtensionService; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; @@ -50,6 +69,8 @@ public class DeviceTypeExtensionServiceComponent { } ctx.getBundleContext() .registerService(DeviceTypeGeneratorService.class, new DeviceTypeGeneratorServiceImpl(), null); + ctx.getBundleContext().registerService(DeviceTypePluginExtensionService.class, + new DeviceTypePluginExtensionServiceImpl(), null); if (log.isDebugEnabled()) { log.debug("Device Type Extension Service Component successfully activated"); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/spi/DeviceTypePluginExtensionService.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/spi/DeviceTypePluginExtensionService.java new file mode 100644 index 0000000000..f91ed2e985 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/spi/DeviceTypePluginExtensionService.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019, Entgra (Pvt) Ltd. (https://entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.extensions.spi; + +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypePluginExtensionException; + +/** + * This represents the device type plugin extension service which can be used by any device type plugin implementation + * intended to use the same plugin DAO instances to be used with its plugin level DAO components + */ +public interface DeviceTypePluginExtensionService { + + /** + * Save device type specific DeviceTypePluginDAOManager in a HashMap againast tenant ID and device type + * @param deviceType - Type of the device (i.e; android, ios, windows) + * @param pluginDAOManager - Device type plugin DAO manager instance to be saved against device type + * @throws DeviceTypePluginExtensionException when pluginDAOManager is null + */ + void addPluginDAOManager(String deviceType, DeviceTypePluginDAOManager pluginDAOManager) + throws DeviceTypePluginExtensionException; + + /** + * Retrieve the DeviceTypePluginDAOManager instance against tenant ID and given device type + * @param deviceType - Type of the device (i.e; android, ios, windows) + * @return an Instance of {@link DeviceTypePluginDAOManager} + * @throws DeviceTypePluginExtensionException when pluginDAOManager cannot be found + */ + DeviceTypePluginDAOManager getPluginDAOManager(String deviceType) throws DeviceTypePluginExtensionException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js index ca8fa6dbd8..c39e797bc2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js @@ -327,15 +327,6 @@ deviceModule = function () { return response; }; - publicMethods.getDeviceTypesConfig = function () { - var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types/config"; - var response = privateMethods.callBackend(url, constants["HTTP_GET"]); - if (response.status == "success") { - response.content = parse(response.content); - } - return response; - }; - /* @Updated */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js index fbba497e09..2448a89f8f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js @@ -506,7 +506,7 @@ function loadDevices(searchType, searchParam) { $('#device-grid').datatables_extended_serverside_paging( null, - serviceURL, + "/api/device-mgt/v1.0/devices/", dataFilter, columns, fnCreatedRow, @@ -525,7 +525,8 @@ function loadDevices(searchType, searchParam) { }, { "placeholder": "Top-Device-Name-Search", - "searchKey": "namePattern" + "searchKey": "namePattern", + "groupId": groupId } ); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js index 94284ac016..692f692302 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devicetype.edit/edit.js @@ -35,7 +35,7 @@ function onRequest(context) { var deviceType = request.getParameter("type"); var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] - + "/device-types/config/" + deviceType; + + "/device-types/" + deviceType; displayData.name = deviceType; serviceInvokers.XMLHttp.get( restAPIEndpoint, 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 3fd2548a6f..320d630efe 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 @@ -210,7 +210,7 @@ $(document).ready(function () { }); deviceType.deviceTypeMetaDefinition.features = features; - var addRoleAPI = apiBasePath + "/admin/device-types"; + var addRoleAPI = apiBasePath + "/admin/device-types/" + deviceType.name; invokerUtil.put( addRoleAPI, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js index aff3ea3942..3f8e0a7b64 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js @@ -76,6 +76,9 @@ $.fn.datatables_extended_serverside_paging = function (settings, url, dataFilter searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value); } if (options) { + if (options.groupId){ + searchParams["groupId"] = options.groupId; + } searchParams[options.searchKey] = encodeURIComponent(params.search.value); } params.filter = JSON.stringify(searchParams); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.device-view/device-view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.device-view/device-view.js index cf716ef35c..a431c66a71 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.device-view/device-view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.device-view/device-view.js @@ -42,7 +42,7 @@ function onRequest(context) { var displayData = {}; var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] - + "/device-types/config/" + deviceType; + + "/device-types/" + deviceType; displayData.deviceType = deviceType; displayData.tenantDomain = tenantDomain; serviceInvokers.XMLHttp.get( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.js index 0f3563bad1..0f24173632 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.default.device.type.type-view/type-view.js @@ -32,7 +32,7 @@ function onRequest(context) { return opts.inverse(this); }); var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] - + "/device-types/config/" + deviceType; + + "/device-types/" + deviceType; displayData.deviceType = deviceType; displayData.tenantDomain = tenantDomain; serviceInvokers.XMLHttp.get( diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/WEB-INF/web.xml b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/WEB-INF/web.xml index 066baa8fa6..f5ba0ae97a 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/WEB-INF/web.xml +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/WEB-INF/web.xml @@ -27,6 +27,10 @@ doAuthentication false + + basicAuth + true + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml index 3fbc48358e..ff85f4c4fd 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml @@ -115,7 +115,35 @@ + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + org.wso2.carbon.devicemgt + io.entgra.device.mgt.ui + ${project.version} + war + true + + ${project.build.directory}/maven-shared-archive-resources/webapps + + entgra.war + **/* + + + + + + - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf index f2fa5b0aaa..7d162718ff 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/src/main/resources/p2.inf @@ -4,4 +4,4 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/uuf-template-app);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggeryapps/uuf-template-app,target:${installFolder}/../../deployment/server/jaggeryapps/uuf-template-app,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggery-modules/utils/,target:${installFolder}/../../modules/utils,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/webapps/store.war,target:${installFolder}/../../deployment/server/webapps/store.war,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/webapps/entgra.war,target:${installFolder}/../../deployment/server/webapps/entgra.war,overwrite:true);\