Merge with upstream

feature/appm-store/pbac
lasanthaDLPDS 5 years ago
commit 40ec702334

@ -55,7 +55,7 @@ public class AuthenticationHandler extends AbstractHandler {
private static final String X_JWT_ASSERTION = "X-JWT-Assertion"; private static final String X_JWT_ASSERTION = "X-JWT-Assertion";
private static final String JWTTOKEN = "JWTToken"; private static final String JWTTOKEN = "JWTToken";
private static final String AUTHORIZATION = "Authorization"; 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 static final String CONTENT_TYPE = "Content-Type";
private IOTServerConfiguration iotServerConfiguration; private IOTServerConfiguration iotServerConfiguration;
@ -95,7 +95,7 @@ public class AuthenticationHandler extends AbstractHandler {
log.debug("Verify Cert:\n" + mdmSignature); log.debug("Verify Cert:\n" + mdmSignature);
} }
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + "ios"); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + "ios");
Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker); Map<String, String> certVerifyHeaders = this.setHeaders();
Certificate certificate = new Certificate(); Certificate certificate = new Certificate();
certificate.setPem(mdmSignature); certificate.setPem(mdmSignature);
@ -127,7 +127,7 @@ public class AuthenticationHandler extends AbstractHandler {
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker); Map<String, String> certVerifyHeaders = this.setHeaders();
Certificate certificate = new Certificate(); Certificate certificate = new Certificate();
certificate.setPem(subjectDN); certificate.setPem(subjectDN);
certificate.setTenantId(tenantId); certificate.setTenantId(tenantId);
@ -157,7 +157,7 @@ public class AuthenticationHandler extends AbstractHandler {
} }
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker); Map<String, String> certVerifyHeaders = this.setHeaders();
Certificate certificate = new Certificate(); Certificate certificate = new Certificate();
certificate.setPem(encodedPem); certificate.setPem(encodedPem);
@ -184,9 +184,6 @@ public class AuthenticationHandler extends AbstractHandler {
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
log.error("Error while processing certificate.", e); log.error("Error while processing certificate.", e);
return false; return false;
} catch (APIMCertificateMGTException e) {
log.error("Error while processing certificate.", e);
return false;
} catch (CertificateException e) { } catch (CertificateException e) {
log.error("Certificate issue occurred when generating converting PEM to x509Certificate", e); log.error("Certificate issue occurred when generating converting PEM to x509Certificate", e);
return false; return false;
@ -212,9 +209,9 @@ public class AuthenticationHandler extends AbstractHandler {
return null; return null;
} }
private Map<String, String> setHeaders(RESTInvoker restInvoker) throws APIMCertificateMGTException { private Map<String, String> setHeaders() {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
String accessToken = Utils.getAccessToken(iotServerConfiguration, restInvoker); String accessToken = Utils.getBase64EncodedToken(iotServerConfiguration);
map.put(AUTHORIZATION, BEARER + accessToken); map.put(AUTHORIZATION, BEARER + accessToken);
map.put(CONTENT_TYPE, "application/json"); map.put(CONTENT_TYPE, "application/json");
return map; return map;

@ -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. * @param iotServerConfiguration Instance of the IoTsererConfiguration.
* @return Access token will be returned. * @return Access token will be returned.
* @throws APIMCertificateMGTException
*/ */
public static String getAccessToken(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker) public static String getBase64EncodedToken(IOTServerConfiguration iotServerConfiguration) {
throws APIMCertificateMGTException { return Base64.encode((iotServerConfiguration.getUsername() + ":" + iotServerConfiguration.getPassword()).
try { getBytes());
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<String, String> 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);
}
} }
/** /**

@ -92,8 +92,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
setMockClient(); setMockClient();
this.mockClient.setResponse(getDCRResponse());
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getValidationResponse()); this.mockClient.setResponse(getValidationResponse());
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration, boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice")); transportHeaders, "https://test.com/testservice/device-mgt/testdevice"));
@ -107,7 +105,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, "Test Header"); transportHeaders.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, "Test Header");
setMockClient(); setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getValidationResponse()); this.mockClient.setResponse(getValidationResponse());
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration, boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice")); transportHeaders, "https://test.com/testservice/device-mgt/testdevice"));
@ -121,7 +118,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header"); transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header");
setMockClient(); setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getValidationResponse()); this.mockClient.setResponse(getValidationResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration, MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
@ -141,7 +137,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient(); setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getValidationResponse()); this.mockClient.setResponse(getValidationResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration, MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
@ -156,7 +151,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient(); setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getInvalidResponse()); this.mockClient.setResponse(getInvalidResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration, MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
@ -185,7 +179,6 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient(); setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(null); this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration, MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); transportHeaders, "https://test.com/testservice/device-mgt/testdevice");

@ -37,6 +37,10 @@
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param>
<param-name>basicAuth</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>

@ -324,9 +324,14 @@ public class CertificateGenerator {
KeyStoreReader keyStoreReader = new KeyStoreReader(); KeyStoreReader keyStoreReader = new KeyStoreReader();
if (distinguishedName != null && !distinguishedName.isEmpty()) { if (distinguishedName != null && !distinguishedName.isEmpty()) {
if (distinguishedName.contains("/CN=")) { if (distinguishedName.contains("/CN=")) {
String[] dnSplits = distinguishedName.split("/CN="); String[] dnSplits = distinguishedName.split("/");
String commonNameExtracted = dnSplits[dnSplits.length - 1]; for (String dnPart : dnSplits) {
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted); if (dnPart.contains("CN=")) {
String commonNameExtracted = dnPart.replace("CN=", "");
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
break;
}
}
} else { } else {
LdapName ldapName; LdapName ldapName;
try { try {

@ -901,12 +901,7 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("device-id") @PathParam("device-id")
@Size(max = 45) @Size(max = 45)
String deviceId, String deviceId);
@ApiParam(
name = "permanentDelete",
value = "Boolean flag indicating whether to permanently delete the device.",
required = false)
@QueryParam("permanentDelete") boolean permanentDelete);
@GET @GET
@Path("/{type}/{id}/features") @Path("/{type}/{id}/features")

@ -15,6 +15,22 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; 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", description = "Update the ownership of the device",
key = "perm:admin:devices:update-enrollment", key = "perm:admin:devices:update-enrollment",
permissions = {"/device-mgt/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.", value = "List of device identifiers.",
required = true) required = true)
List<String> deviceIdentifiers); List<String> 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);
} }

@ -105,7 +105,6 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map;
@Path("/devices") @Path("/devices")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -326,8 +325,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@Override @Override
@Path("/type/{device-type}/id/{device-id}") @Path("/type/{device-type}/id/{device-id}")
public Response deleteDevice(@PathParam("device-type") String deviceType, public Response deleteDevice(@PathParam("device-type") String deviceType,
@PathParam("device-id") String deviceId, @PathParam("device-id") String deviceId) {
@QueryParam("permanentDelete") boolean permanentDelete) {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService(); DeviceMgtAPIUtils.getDeviceManagementService();
try { try {
@ -336,16 +334,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
if (persistedDevice == null) { if (persistedDevice == null) {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
} }
boolean response = deviceManagementProviderService.disenrollDevice(deviceIdentifier);
boolean response;
if (permanentDelete) {
response = deviceManagementProviderService.deleteDevice(deviceIdentifier);
} else {
response = deviceManagementProviderService.disenrollDevice(deviceIdentifier);
}
return Response.status(Response.Status.OK).entity(response).build(); return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error encountered while deleting device of type : " + deviceType + " and " + String msg = "Error encountered while deleting device of type : " + deviceType + " and " +
"ID : " + deviceId; "ID : " + deviceId;

@ -15,6 +15,22 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; 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.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; 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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; 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.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; 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(); 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();
}
}
} }

@ -140,7 +140,8 @@ public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagemen
@Override @Override
@PUT @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 != null && deviceType.getDeviceTypeMetaDefinition() != null) {
if (deviceType.getName() == null || !deviceType.getName().equals(type)) { if (deviceType.getName() == null || !deviceType.getName().equals(type)) {
return Response.status(Response.Status.BAD_REQUEST).entity("Type name mismatch. Expected: '" + type + return Response.status(Response.Status.BAD_REQUEST).entity("Type name mismatch. Expected: '" + type +
@ -166,7 +167,10 @@ public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagemen
} }
@Override @Override
public Response addDeviceTypePlatformConfig(String type, PlatformConfiguration platformConfiguration) { @POST
@Path("/{type}/configs")
public Response addDeviceTypePlatformConfig(@PathParam("type") String type,
PlatformConfiguration platformConfiguration) {
boolean isSaved; boolean isSaved;
if (platformConfiguration.getType() == null || !platformConfiguration.getType().equals(type)) { if (platformConfiguration.getType() == null || !platformConfiguration.getType().equals(type)) {
return Response.status(Response.Status.BAD_REQUEST).entity("Type name mismatch. Expected: '" + type + return Response.status(Response.Status.BAD_REQUEST).entity("Type name mismatch. Expected: '" + type +

@ -481,8 +481,7 @@ public class DeviceManagementServiceImplTest {
public void testDeleteDevice() { public void testDeleteDevice() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString() Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
, false);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -492,8 +491,7 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean())).thenReturn(null); .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean())).thenReturn(null);
Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString() Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
, false);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
Mockito.reset(this.deviceManagementProviderService); Mockito.reset(this.deviceManagementProviderService);
} }
@ -504,8 +502,7 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any(DeviceIdentifier.class))) Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceManagementException()); .thenThrow(new DeviceManagementException());
Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString() Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
, false);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
Mockito.reset(this.deviceManagementProviderService); Mockito.reset(this.deviceManagementProviderService);
} }

@ -277,6 +277,17 @@ public interface DeviceDAO {
*/ */
List<Device> getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; List<Device> 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<Device> searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
/** /**
* This method is used to retrieve all the devices of a given tenant and device type. * This method is used to retrieve all the devices of a given tenant and device type.
* *

@ -153,6 +153,137 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> 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 @Override
public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId) public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {

@ -159,6 +159,137 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> 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 @Override
public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId) public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {

@ -140,6 +140,136 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> 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 @Override
public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId) public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {

@ -156,6 +156,136 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> 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 @Override
public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId) public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {

@ -827,7 +827,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} else { } else {
try { try {
DeviceManagementDAOFactory.openConnection(); 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); count = deviceDAO.getDeviceCount(request, tenantId);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving device list pertaining to the current tenant"; String msg = "Error occurred while retrieving device list pertaining to the current tenant";

@ -34,6 +34,7 @@
*/ */
package org.wso2.carbon.device.mgt.extensions.device.type.template; 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; 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.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.DeviceTypeDeployerPayloadException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; 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.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.DeviceTypePluginConstants;
import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; 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.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.RegistryException;
import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.utils.CarbonUtils; 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 @Override
@ -307,15 +339,11 @@ public class DeviceTypeManager implements DeviceManager {
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
} }
} catch (DeviceTypeMgtPluginException e) { } catch (DeviceTypeMgtPluginException e) {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
} catch (DeviceTypeMgtPluginException ex) {
String msg = "Error occurred while roll back the device enrol transaction :" +
device.toString();
log.warn(msg, ex);
}
String msg = "Error while enrolling the " + deviceType + " device : " + device.getDeviceIdentifier(); String msg = "Error while enrolling the " + deviceType + " device : " + device.getDeviceIdentifier();
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} finally {
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} }
return status; return status;
} }
@ -334,16 +362,12 @@ public class DeviceTypeManager implements DeviceManager {
status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(device); status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(device);
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
} catch (DeviceTypeMgtPluginException e) { } catch (DeviceTypeMgtPluginException e) {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
} catch (DeviceTypeMgtPluginException mobileDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" +
device.toString();
log.warn(msg, mobileDAOEx);
}
String msg = "Error while updating the enrollment of the " + deviceType + " device : " + String msg = "Error while updating the enrollment of the " + deviceType + " device : " +
device.getDeviceIdentifier(); device.getDeviceIdentifier();
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} finally {
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} }
return status; return status;
} }
@ -378,13 +402,7 @@ public class DeviceTypeManager implements DeviceManager {
deviceId.getId(); deviceId.getId();
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} finally { } finally {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
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);
}
} }
return isEnrolled; return isEnrolled;
} }
@ -419,12 +437,7 @@ public class DeviceTypeManager implements DeviceManager {
throw new DeviceManagementException( throw new DeviceManagementException(
"Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e); "Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e);
} finally { } finally {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} catch (DeviceTypeMgtPluginException e) {
String msg = "Error occurred while closing the transaction to get device " + deviceId.getId();
log.warn(msg, e);
}
} }
return device; return device;
} }
@ -447,14 +460,11 @@ public class DeviceTypeManager implements DeviceManager {
status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(updatedDevice); status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(updatedDevice);
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
} catch (DeviceTypeMgtPluginException e) { } catch (DeviceTypeMgtPluginException e) {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
} catch (DeviceTypeMgtPluginException transactionException) {
String msg = "Error occurred while rolling back transaction for device: " + deviceId.getId();
log.warn(msg, transactionException);
}
throw new DeviceManagementException( throw new DeviceManagementException(
"Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e); "Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e);
} finally {
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} }
} }
return status; return status;
@ -544,15 +554,12 @@ public class DeviceTypeManager implements DeviceManager {
status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(existingDevice); status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(existingDevice);
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
} catch (DeviceTypeMgtPluginException e) { } catch (DeviceTypeMgtPluginException e) {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
} catch (DeviceTypeMgtPluginException e1) {
log.warn("Error occurred while roll back the update device info transaction : '" +
device.toString() + "'", e1);
}
throw new DeviceManagementException( throw new DeviceManagementException(
"Error occurred while updating the " + deviceType + " device: '" + "Error occurred while updating the " + deviceType + " device: '" +
device.getDeviceIdentifier() + "'", e); device.getDeviceIdentifier() + "'", e);
} finally {
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} }
return status; return status;
} }
@ -572,12 +579,7 @@ public class DeviceTypeManager implements DeviceManager {
} catch (DeviceTypeMgtPluginException e) { } catch (DeviceTypeMgtPluginException e) {
throw new DeviceManagementException("Error occurred while fetching all " + deviceType + " devices", e); throw new DeviceManagementException("Error occurred while fetching all " + deviceType + " devices", e);
} finally { } finally {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} catch (DeviceTypeMgtPluginException e) {
String msg = "Error occurred while closing the transaction to get all devices.";
log.warn(msg, e);
}
} }
return devices; return devices;
} }
@ -600,15 +602,12 @@ public class DeviceTypeManager implements DeviceManager {
status = deviceTypePluginDAOManager.getDeviceDAO().deleteDevice(existingDevice); status = deviceTypePluginDAOManager.getDeviceDAO().deleteDevice(existingDevice);
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction(); deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
} catch (DeviceTypeMgtPluginException e) { } catch (DeviceTypeMgtPluginException e) {
try { deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
} catch (DeviceTypeMgtPluginException e1) {
log.warn("Error occurred while roll back the delete device info transaction : '" +
device.toString() + "'", e1);
}
throw new DeviceManagementException( throw new DeviceManagementException(
"Error occurred while deleting the " + deviceType + " device: '" + "Error occurred while deleting the " + deviceType + " device: '" +
device.getDeviceIdentifier() + "'", e); device.getDeviceIdentifier() + "'", e);
} finally {
deviceTypePluginDAOManager.getDeviceTypeDAOHandler().closeConnection();
} }
return status; return status;
} }

@ -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<String, DeviceTypePluginDAOManager> 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);
}
}
}

@ -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; package org.wso2.carbon.device.mgt.extensions.device.type.template.dao;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.DeviceTypeDeployerPayloadException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException;
@ -31,7 +49,26 @@ public class DeviceTypeDAOHandler {
Context ctx = new InitialContext(); Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(datasourceName); dataSource = (DataSource) ctx.lookup(datasourceName);
} catch (NamingException e) { } 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); conn.setAutoCommit(false);
currentConnection.set(conn); currentConnection.set(conn);
} catch (SQLException e) { } 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 { try {
currentConnection.set(dataSource.getConnection()); currentConnection.set(dataSource.getConnection());
} catch (SQLException e) { } 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(); 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 { try {
Connection conn = currentConnection.get(); conn.commit();
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");
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceTypeMgtPluginException("Error occurred while committing the transaction", e); String msg = "Error occurred while committing the transaction.";
} finally { log.error(msg, e);
closeConnection();
} }
} }
public void closeConnection() throws DeviceTypeMgtPluginException { public void closeConnection() {
Connection con = currentConnection.get(); Connection con = currentConnection.get();
if (con != null) { if (con != null) {
try { try {
con.close(); con.close();
} catch (SQLException e) { } 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(); 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 { try {
Connection conn = currentConnection.get(); conn.rollback();
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");
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceTypeMgtPluginException("Error occurred while rollback the transaction", e); String msg = "Error occurred while roll-backing the transaction.";
} finally { log.error(msg, e);
closeConnection();
} }
} }
} }

@ -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);
}
}

@ -14,6 +14,23 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; 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.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; 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.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.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
@ -50,6 +69,8 @@ public class DeviceTypeExtensionServiceComponent {
} }
ctx.getBundleContext() ctx.getBundleContext()
.registerService(DeviceTypeGeneratorService.class, new DeviceTypeGeneratorServiceImpl(), null); .registerService(DeviceTypeGeneratorService.class, new DeviceTypeGeneratorServiceImpl(), null);
ctx.getBundleContext().registerService(DeviceTypePluginExtensionService.class,
new DeviceTypePluginExtensionServiceImpl(), null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Device Type Extension Service Component successfully activated"); log.debug("Device Type Extension Service Component successfully activated");
} }

@ -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;
}

@ -327,15 +327,6 @@ deviceModule = function () {
return response; 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 @Updated
*/ */

@ -506,7 +506,7 @@ function loadDevices(searchType, searchParam) {
$('#device-grid').datatables_extended_serverside_paging( $('#device-grid').datatables_extended_serverside_paging(
null, null,
serviceURL, "/api/device-mgt/v1.0/devices/",
dataFilter, dataFilter,
columns, columns,
fnCreatedRow, fnCreatedRow,
@ -525,7 +525,8 @@ function loadDevices(searchType, searchParam) {
}, { }, {
"placeholder": "Top-Device-Name-Search", "placeholder": "Top-Device-Name-Search",
"searchKey": "namePattern" "searchKey": "namePattern",
"groupId": groupId
} }
); );

@ -35,7 +35,7 @@ function onRequest(context) {
var deviceType = request.getParameter("type"); var deviceType = request.getParameter("type");
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/device-types/config/" + deviceType; + "/device-types/" + deviceType;
displayData.name = deviceType; displayData.name = deviceType;
serviceInvokers.XMLHttp.get( serviceInvokers.XMLHttp.get(
restAPIEndpoint, restAPIEndpoint,

@ -210,7 +210,7 @@ $(document).ready(function () {
}); });
deviceType.deviceTypeMetaDefinition.features = features; deviceType.deviceTypeMetaDefinition.features = features;
var addRoleAPI = apiBasePath + "/admin/device-types"; var addRoleAPI = apiBasePath + "/admin/device-types/" + deviceType.name;
invokerUtil.put( invokerUtil.put(
addRoleAPI, addRoleAPI,

@ -76,6 +76,9 @@ $.fn.datatables_extended_serverside_paging = function (settings, url, dataFilter
searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value); searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value);
} }
if (options) { if (options) {
if (options.groupId){
searchParams["groupId"] = options.groupId;
}
searchParams[options.searchKey] = encodeURIComponent(params.search.value); searchParams[options.searchKey] = encodeURIComponent(params.search.value);
} }
params.filter = JSON.stringify(searchParams); params.filter = JSON.stringify(searchParams);

@ -42,7 +42,7 @@ function onRequest(context) {
var displayData = {}; var displayData = {};
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/device-types/config/" + deviceType; + "/device-types/" + deviceType;
displayData.deviceType = deviceType; displayData.deviceType = deviceType;
displayData.tenantDomain = tenantDomain; displayData.tenantDomain = tenantDomain;
serviceInvokers.XMLHttp.get( serviceInvokers.XMLHttp.get(

@ -32,7 +32,7 @@ function onRequest(context) {
return opts.inverse(this); return opts.inverse(this);
}); });
var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/device-types/config/" + deviceType; + "/device-types/" + deviceType;
displayData.deviceType = deviceType; displayData.deviceType = deviceType;
displayData.tenantDomain = tenantDomain; displayData.tenantDomain = tenantDomain;
serviceInvokers.XMLHttp.get( serviceInvokers.XMLHttp.get(

@ -27,6 +27,10 @@
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>false</param-value> <param-value>false</param-value>
</context-param> </context-param>
<context-param>
<param-name>basicAuth</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>

@ -115,7 +115,35 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.device.mgt.ui</artifactId>
<version>${project.version}</version>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps
</outputDirectory>
<destFileName>entgra.war</destFileName>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

@ -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.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}/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}/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);\

Loading…
Cancel
Save