From ad7fa09e32fa33ff00b580fe6bda354bc6c9b613 Mon Sep 17 00:00:00 2001 From: hasuniea Date: Thu, 26 May 2016 18:11:07 +0530 Subject: [PATCH 01/18] add certificate service --- .../pom.xml | 2 +- .../mgt/jaxrs/api/CertificateMgtService.java | 2 +- .../api/impl/CertificateMgtServiceImpl.java | 5 +- .../pom.xml | 209 ++++++++++++++++++ .../mgt/cert/jaxrs/api/Certificate.java | 123 +++++++++++ .../api/beans/EnrollmentCertificate.java | 34 +++ .../cert/jaxrs/api/common/ErrorHandler.java | 33 +++ .../cert/jaxrs/api/common/ErrorMessage.java | 42 ++++ .../api/common/GsonMessageBodyHandler.java | 95 ++++++++ .../jaxrs/api/common/MDMAPIException.java | 59 +++++ .../api/exception/BadRequestException.java | 31 +++ .../mgt/cert/jaxrs/api/exception/Message.java | 41 ++++ .../cert/jaxrs/api/impl/CertificateImpl.java | 181 +++++++++++++++ .../jaxrs/api/util/DeviceMgtAPIUtils.java | 75 +++++++ .../cert/jaxrs/api/util/ResponsePayload.java | 107 +++++++++ .../src/main/webapp/META-INF/permissions.xml | 67 ++++++ .../webapp/META-INF/webapp-classloading.xml | 35 +++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 66 ++++++ .../src/main/webapp/WEB-INF/web.xml | 66 ++++++ components/certificate-mgt/pom.xml | 1 + .../pom.xml | 123 +++++++++++ .../src/main/resources/build.properties | 1 + .../src/main/resources/p2.inf | 2 + features/certificate-mgt/pom.xml | 1 + 24 files changed, 1395 insertions(+), 6 deletions(-) create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/permissions.xml create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/webapp-classloading.xml create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/cxf-servlet.xml create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/web.xml create mode 100644 features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml create mode 100644 features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/build.properties create mode 100644 features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml index 546fdd32b5c..a36f912d2a5 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml @@ -31,7 +31,7 @@ 4.0.0 org.wso2.carbon.certificate.mgt.api war - WSO2 Carbon - Mobile Device Management API + WSO2 Carbon - Certificate Management API WSO2 Carbon - Certificate Management API http://wso2.org diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java index c0ba1d929a6..6c9abc27b61 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java @@ -13,7 +13,7 @@ public interface CertificateMgtService { * @return X509Certificate type sign certificate. */ @POST - @Path("csr-sign") + @Path("signcsr") @Produces({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN}) @Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN}) Response getSignedCertFromCSR(String binarySecurityToken); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java index 082f203bf25..e0ca24de02d 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java @@ -8,10 +8,7 @@ import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; import org.wso2.carbon.certificate.mgt.jaxrs.api.CertificateMgtService; import org.wso2.carbon.certificate.mgt.jaxrs.exception.Message; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.security.cert.CertificateEncodingException; diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml new file mode 100644 index 00000000000..3528287e95a --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml @@ -0,0 +1,209 @@ + + + + + + + certificate-mgt + org.wso2.carbon.devicemgt + 1.1.1-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.certificate.mgt.cert.adminapi + war + WSO2 Carbon - Admin Certificate Management API + WSO2 Carbon - Admin Certificate Management API + http://wso2.org + + + + + maven-compiler-plugin + + 1.7 + 1.7 + + + + maven-war-plugin + + WEB-INF/lib/*cxf*.jar + admin-certificate + + + + org.apache.felix + maven-scr-plugin + + + + + + + deploy + + compile + + + org.apache.maven.plugins + maven-antrun-plugin + 1.7 + + + compile + + run + + + + + + + + + + + + + + + + + + client + + test + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + test + + java + + + + + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + + + commons-codec.wso2 + commons-codec + + + commons-codec + commons-codec + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + org.apache.cxf + cxf-rt-transports-http + + + junit + junit + test + + + javax.ws.rs + jsr311-api + provided + + + org.wso2.carbon + org.wso2.carbon.logging + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.apache.axis2.wso2 + axis2-client + + + org.apache.neethi.wso2 + neethi + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + provided + + + io.swagger + swagger-annotations + + + io.swagger + swagger-core + + + org.slf4j + slf4j-api + + + + + io.swagger + swagger-jaxrs + + + javax.servlet + servlet-api + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + provided + + + + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java new file mode 100644 index 00000000000..1192cdfa132 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java @@ -0,0 +1,123 @@ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api; + +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.device.mgt.common.PaginationResult; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +public interface Certificate { + + /** + * Save a list of certificates and relevant information in the database. + * + * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as + * a pem and a serial number. + * @return Status of the data persist operation. + */ + @POST + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Adding an SSL Certificate", + notes = "Add a new SSL certificate to the client end database") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Added successfully"), + @ApiResponse(code = 500, message = "Error occurred while saving the certificate") + }) + @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"}) + Response saveCertificate(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "enrollmentCertificates", value = "certificate with serial, " + + "pem and tenant id", required = true) EnrollmentCertificate[] + enrollmentCertificates); + + /** + * Get a certificate when the serial number is given. + * + * @param serialNumber serial of the certificate needed. + * @return certificate response. + */ + @GET + @Path("{serialNumber}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting Details of an SSL Certificate", + notes = "Get the client side SSL certificate details", + response = CertificateResponse.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = CertificateResponse.class), + @ApiResponse(code = 400, message = "Notification status updated successfully"), + @ApiResponse(code = 500, message = "Error occurred while converting PEM file to X509Certificate") + }) + @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) + Response getCertificate(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "serialNumber", value = "Provide the serial number of the " + + "certificate that you wish to get the details of", required = true) + @PathParam("serialNumber") String serialNumber); + + /** + * Get all certificates in a paginated manner. + * + * @param startIndex index of the first record to be fetched + * @param length number of records to be fetched starting from the start index. + * @return paginated result of certificate. + * @throws MDMAPIException + */ + @GET + @Path("paginate") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting the Certificate Details in a Paginated Manner", + notes = "You will have many certificates used for mutual SSL. In a situation where you wish to " + + "view all the certificate details, it is not feasible to show all the details on one " + + "page therefore the details are paginated", + response = PaginationResult.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = PaginationResult.class), + @ApiResponse(code = 400, message = "Invalid start index"), + @ApiResponse(code = 400, message = "Invalid length value"), + @ApiResponse(code = 500, message = "Error occurred while fetching all certificates") + }) + @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) + Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "start", + value = "Provide the starting pagination index as the value", required = true) + @QueryParam("start") int startIndex, + @ApiParam(name = "length", value = "Provide how many certificate details you" + + " require from the starting pagination index as the value", + required = true) @QueryParam("length") int length) throws MDMAPIException; + + @DELETE + @Path("{serialNumber}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "DELETE", + value = "Deleting an SSL Certificate", + notes = "Delete an SSL certificate that's on the client end", + response = boolean.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 400, message = "Invalid start index"), + @ApiResponse(code = 500, message = "Error when deleting the certificate" + ) }) + @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"}) + Response removeCertificate(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "serialNumber", value = "Provide the serial number of the " + + "certificate that you wish to delete", required = true) + @PathParam("serialNumber") String serialNumber) throws MDMAPIException; + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java new file mode 100644 index 00000000000..a687a259bb1 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java @@ -0,0 +1,34 @@ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; + +/** + * Created by hasunie on 5/26/16. + */ +public class EnrollmentCertificate { + String serial; + String pem; + int tenantId; + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getSerial() { + return serial; + } + + public void setSerial(String serial) { + this.serial = serial; + } + + public String getPem() { + return pem; + } + + public void setPem(String pem) { + this.pem = pem; + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java new file mode 100644 index 00000000000..25d9e4ad797 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.common; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +@Produces({ "application/json", "application/xml" }) +public class ErrorHandler implements ExceptionMapper { + + public Response toResponse(MDMAPIException exception) { + ErrorMessage errorMessage = new ErrorMessage(); + errorMessage.setErrorMessage(exception.getErrorMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java new file mode 100644 index 00000000000..3bbb36969d9 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.common; + + +public class ErrorMessage { + + private String errorMessage; + private String errorCode; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java new file mode 100644 index 00000000000..6abb296c175 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.common; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import java.io.*; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; + +@Provider +@Produces(APPLICATION_JSON) +@Consumes(APPLICATION_JSON) +public class GsonMessageBodyHandler implements MessageBodyWriter, MessageBodyReader { + + private Gson gson; + private static final String UTF_8 = "UTF-8"; + + public boolean isReadable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { + return true; + } + + private Gson getGson() { + if (gson == null) { + final GsonBuilder gsonBuilder = new GsonBuilder(); + gson = gsonBuilder.create(); + } + return gson; + } + + public Object readFrom(Class objectClass, Type type, Annotation[] annotations, MediaType mediaType, + MultivaluedMap stringStringMultivaluedMap, InputStream entityStream) + throws IOException, WebApplicationException { + + InputStreamReader reader = new InputStreamReader(entityStream, "UTF-8"); + + try { + return getGson().fromJson(reader, type); + } finally { + reader.close(); + } + } + + public boolean isWriteable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { + return true; + } + + public long getSize(Object o, Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { + return -1; + } + + public void writeTo(Object object, Class aClass, Type type, Annotation[] annotations, MediaType mediaType, + MultivaluedMap stringObjectMultivaluedMap, OutputStream entityStream) + throws IOException, WebApplicationException { + + OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8); + try { + Type jsonType = null; + if (type.equals(type)) { + jsonType = type; + } + getGson().toJson(object, jsonType, writer); + } finally { + writer.close(); + } + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java new file mode 100644 index 00000000000..6a27e76fcb6 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.common; + +/** + * Custom exception class for handling CDM API related exceptions. + */ +public class MDMAPIException extends Exception { + + private static final long serialVersionUID = 7950151650447893900L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public MDMAPIException(String msg, Exception e) { + super(msg, e); + setErrorMessage(msg); + } + + public MDMAPIException(String msg, Throwable cause) { + super(msg, cause); + setErrorMessage(msg); + } + + public MDMAPIException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public MDMAPIException() { + super(); + } + + public MDMAPIException(Throwable cause) { + super(cause); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java new file mode 100644 index 00000000000..6c358cba36f --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.exception; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +public class BadRequestException extends WebApplicationException { + + public BadRequestException(Message message, MediaType mediaType) { + super(Response.status(Response.Status.BAD_REQUEST).entity(message).type(mediaType).build()); + } + +} \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java new file mode 100644 index 00000000000..081a99377b7 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.exception; + +public class Message { + + private String errorMessage; + private String discription; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getDiscription() { + return discription; + } + + public void setDiscription(String discription) { + this.discription = discription; + } +} \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java new file mode 100644 index 00000000000..d97d5ab4b1f --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java @@ -0,0 +1,181 @@ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.Certificate; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.exception.Message; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +public class CertificateImpl implements Certificate { + + private static Log log = LogFactory.getLog(CertificateImpl.class); + + /** + * Save a list of certificates and relevant information in the database. + * + * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as + * a pem and a serial number. + * @return Status of the data persist operation. + */ + @POST + public Response saveCertificate(@HeaderParam("Accept") String acceptHeader, + EnrollmentCertificate[] enrollmentCertificates) { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + CertificateManagementService certificateService; + List certificates = new ArrayList<>(); + org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; + certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + try { + for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { + certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); + certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + certificate.setSerial(enrollmentCertificate.getSerial()); + certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); + certificates.add(certificate); + } + certificateService.saveCertificate(certificates); + return Response.status(Response.Status.CREATED).entity("Added successfully."). + type(responseMediaType).build(); + } catch (KeystoreException e) { + String msg = "Error occurred while converting PEM file to X509Certificate."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } + + /** + * Get a certificate when the serial number is given. + * + * @param serialNumber serial of the certificate needed. + * @return certificate response. + */ + @GET + @Path("{serialNumber}") + public Response getCertificate(@HeaderParam("Accept") String acceptHeader, + @PathParam("serialNumber") String serialNumber) { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + Message message = new Message(); + + if (serialNumber == null || serialNumber.isEmpty()) { + message.setErrorMessage("Invalid serial number"); + message.setDiscription("Serial number is missing or invalid."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + List certificateResponse; + try { + certificateResponse = certificateService.searchCertificates(serialNumber); + return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } + + /** + * Get all certificates in a paginated manner. + * + * @param startIndex index of the first record to be fetched + * @param length number of records to be fetched starting from the start index. + * @return paginated result of certificate. + * @throws MDMAPIException + */ + @GET + @Path("paginate") + public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, + @QueryParam("start") int startIndex, + @QueryParam("length") int length) + throws MDMAPIException { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + Message message = new Message(); + + if (startIndex < 0) { + message.setErrorMessage("Invalid start index."); + message.setDiscription("Start index cannot be less that 0."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } else if (length <= 0) { + message.setErrorMessage("Invalid length value."); + message.setDiscription("Length should be a positive integer."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + PaginationRequest paginationRequest = new PaginationRequest(startIndex, length); + try { + PaginationResult certificates = certificateService.getAllCertificates(paginationRequest); + return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while fetching all certificates."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } + + /** + * Get all certificates + * + * @return certificate details in an array. + * @throws MDMAPIException + */ + @GET + public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader) + throws MDMAPIException { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + try { + List certificates = certificateService.getCertificates(); + return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while fetching all certificates."; + log.error(msg, e); + throw new MDMAPIException(msg, e); + } + } + + @DELETE + @Path("{serialNumber}") + public Response removeCertificate(@HeaderParam("Accept") String acceptHeader, + @PathParam("serialNumber") String serialNumber) throws MDMAPIException { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + Message message = new Message(); + + if (serialNumber == null || serialNumber.isEmpty()) { + message.setErrorMessage("Invalid serial number"); + message.setDiscription("Serial number is missing or invalid."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + boolean deleted; + try { + deleted = certificateService.removeCertificate(serialNumber); + if(deleted){ + return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build(); + } else { + return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build(); + } + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java new file mode 100644 index 00000000000..40026011f13 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; + +import javax.ws.rs.core.MediaType; + +/** + * DMAPIUtils class provides utility function used by CDM REST-API classes. + */ +public class DeviceMgtAPIUtils { + + public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE; + private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class); + + public static CertificateManagementService getCertificateManagementService() { + + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + CertificateManagementService certificateManagementService = (CertificateManagementService) + ctx.getOSGiService(CertificateManagementService.class, null); + + if (certificateManagementService == null) { + String msg = "CertificateImpl Management service not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + + return certificateManagementService; + } + + + public static MediaType getResponseMediaType(String acceptHeader) { + MediaType responseMediaType; + if (acceptHeader == null || MediaType.WILDCARD.equals(acceptHeader)) { + responseMediaType = DEFAULT_CONTENT_TYPE; + } else { + responseMediaType = MediaType.valueOf(acceptHeader); + } + + return responseMediaType; + } + + public static SearchManagerService getSearchManagerService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + SearchManagerService searchManagerService = + (SearchManagerService) ctx.getOSGiService(SearchManagerService.class, null); + if (searchManagerService == null) { + String msg = "DeviceImpl search manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return searchManagerService; + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java new file mode 100644 index 00000000000..c0f44afd418 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.certificate.mgt.cert.jaxrs.api.util; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class ResponsePayload { + + private int statusCode; + private String messageFromServer; + private Object responseContent; + + @XmlElement + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + @XmlElement + public String getMessageFromServer() { + return messageFromServer; + } + + public void setMessageFromServer(String messageFromServer) { + this.messageFromServer = messageFromServer; + } + + @XmlElement + public Object getResponseContent() { + return responseContent; + } + + public void setResponseContent(Object responseContent) { + this.responseContent = responseContent; + } + + private ResponsePayloadBuilder getBuilder() { + return new ResponsePayloadBuilder(); + } + + public static ResponsePayloadBuilder statusCode(int statusCode) { + ResponsePayload message = new ResponsePayload(); + return message.getBuilder().statusCode(statusCode); + } + + public static ResponsePayloadBuilder messageFromServer(String messageFromServer) { + ResponsePayload message = new ResponsePayload(); + return message.getBuilder().messageFromServer(messageFromServer); + } + + public static ResponsePayloadBuilder responseContent(String responseContent) { + ResponsePayload message = new ResponsePayload(); + return message.getBuilder().responseContent(responseContent); + } + + public class ResponsePayloadBuilder { + + private int statusCode; + private String messageFromServer; + private Object responseContent; + + public ResponsePayloadBuilder statusCode(int statusCode) { + this.statusCode = statusCode; + return this; + } + + public ResponsePayloadBuilder messageFromServer(String messageFromServer) { + this.messageFromServer = messageFromServer; + return this; + } + + public ResponsePayloadBuilder responseContent(String responseContent) { + this.responseContent = responseContent; + return this; + } + + public ResponsePayload build() { + ResponsePayload payload = new ResponsePayload(); + payload.setStatusCode(statusCode); + payload.setMessageFromServer(messageFromServer); + payload.setResponseContent(responseContent); + return payload; + } + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/permissions.xml new file mode 100644 index 00000000000..955b726ad43 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/permissions.xml @@ -0,0 +1,67 @@ + + + + + + + + + get certificate in the database + /device-mgt/emm-admin/certificate/GetSignCSR + /certificates/signcsr + POST + emm_admin + + + + + Save certificate in the database + /device-mgt/admin/certificate/save + /certificates + POST + + + get certificate in the database + /device-mgt/admin/certificate/Get + /certificates/* + GET + + + get certificate in the database + /device-mgt/admin/certificate/GetAll + /certificates + GET + + + get certificate in the database + /device-mgt/admin/certificate/Get + /certificates/* + DELETE + + + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/webapp-classloading.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000000..ed2ed216247 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,35 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000000..fc3c9ef2401 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/web.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..0b5d5b28bf3 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,66 @@ + + + + Certificate-Webapp + + JAX-WS/JAX-RS Certificate Management Endpoint + JAX-WS/JAX-RS Servlet + CXFServlet + + org.apache.cxf.transport.servlet.CXFServlet + + + + CXFServlet + /* + + + 60 + + + + isAdminService + false + + + doAuthentication + true + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + + + CertificateMgt-Admin + /* + + + CONFIDENTIAL + + + + diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index a8fa2df2ce4..6377a0bd9fe 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -37,6 +37,7 @@ org.wso2.carbon.certificate.mgt.core org.wso2.carbon.certificate.mgt.api + org.wso2.carbon.certificate.mgt.cert.adminapi diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml new file mode 100644 index 00000000000..d3648613206 --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml @@ -0,0 +1,123 @@ + + + + + + + org.wso2.carbon.devicemgt + certificate-mgt-feature + 1.1.1-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.certificate.mgt.cert.adminapi.feature + pom + WSO2 Carbon - Admin Certificate Management API Feature + http://wso2.org + This feature contains the APIs required for Admin Certificate Management. + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.cert.adminapi + + ${project.version} + war + true + + ${project.build.directory}/maven-shared-archive-resources/webapps + + admin-certificate.war + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.carbon.certificate.mgt.cert.adminapi + ../../../features/etc/feature.properties + + + + org.wso2.carbon.p2.category.type:server + + org.eclipse.equinox.p2.type.group:false + + + + + + + + + + + diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/build.properties b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/build.properties new file mode 100644 index 00000000000..9c86577d768 --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/build.properties @@ -0,0 +1 @@ +custom = true diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf new file mode 100644 index 00000000000..ad3dd764037 --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf @@ -0,0 +1,2 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.adminapi_${feature.version}/webapps/admin-certificate.war,target:${installFolder}/../../deployment/server/webapps/admin-certificate.war,overwrite:true);\ \ No newline at end of file diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 5b41d935dc8..026c3d06b18 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -37,6 +37,7 @@ org.wso2.carbon.certificate.mgt.server.feature org.wso2.carbon.certificate.mgt.api.feature + org.wso2.carbon.certificate.mgt.cert.adminapi.feature From 271170c26e46d80090cdf17b55caf477cadcc4e2 Mon Sep 17 00:00:00 2001 From: hasuniea Date: Fri, 27 May 2016 18:42:24 +0530 Subject: [PATCH 02/18] refactored cert feature --- .../pom.xml | 2 +- .../carbon/certificate/mgt/cert/jaxrs/api/Certificate.java | 0 .../mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java | 0 .../certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java | 0 .../certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java | 0 .../mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java | 0 .../mgt/cert/jaxrs/api/common/MDMAPIException.java | 0 .../mgt/cert/jaxrs/api/exception/BadRequestException.java | 0 .../certificate/mgt/cert/jaxrs/api/exception/Message.java | 0 .../mgt/cert/jaxrs/api/impl/CertificateImpl.java | 0 .../mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java | 0 .../mgt/cert/jaxrs/api/util/ResponsePayload.java | 0 .../src/main/webapp/META-INF/permissions.xml | 0 .../src/main/webapp/META-INF/webapp-classloading.xml | 0 .../src/main/webapp/WEB-INF/cxf-servlet.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 components/certificate-mgt/pom.xml | 2 +- .../pom.xml | 6 +++--- .../src/main/resources/build.properties | 0 .../src/main/resources/p2.inf | 2 ++ .../src/main/resources/p2.inf | 2 -- features/certificate-mgt/pom.xml | 2 +- 22 files changed, 8 insertions(+), 8 deletions(-) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/pom.xml (99%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/webapp/META-INF/permissions.xml (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/webapp/META-INF/webapp-classloading.xml (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/webapp/WEB-INF/cxf-servlet.xml (100%) rename components/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi => org.wso2.carbon.certificate.mgt.cert.admin.api}/src/main/webapp/WEB-INF/web.xml (100%) rename features/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi.feature => org.wso2.carbon.certificate.mgt.cert.admin.api.feature}/pom.xml (97%) rename features/certificate-mgt/{org.wso2.carbon.certificate.mgt.cert.adminapi.feature => org.wso2.carbon.certificate.mgt.cert.admin.api.feature}/src/main/resources/build.properties (100%) create mode 100644 features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf delete mode 100644 features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml similarity index 99% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index 3528287e95a..3b5c4a9a951 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -29,7 +29,7 @@ 4.0.0 - org.wso2.carbon.certificate.mgt.cert.adminapi + org.wso2.carbon.certificate.mgt.cert.admin.api war WSO2 Carbon - Admin Certificate Management API WSO2 Carbon - Admin Certificate Management API diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorHandler.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/ErrorMessage.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/GsonMessageBodyHandler.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/common/MDMAPIException.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/BadRequestException.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/exception/Message.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ResponsePayload.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/permissions.xml rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/webapp-classloading.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/webapp-classloading.xml similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/META-INF/webapp-classloading.xml rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/webapp-classloading.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/cxf-servlet.xml rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/web.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi/src/main/webapp/WEB-INF/web.xml rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/web.xml diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index 6377a0bd9fe..94b57794e11 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -37,7 +37,7 @@ org.wso2.carbon.certificate.mgt.core org.wso2.carbon.certificate.mgt.api - org.wso2.carbon.certificate.mgt.cert.adminapi + org.wso2.carbon.certificate.mgt.cert.admin.api diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml similarity index 97% rename from features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml rename to features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index d3648613206..99c4ebe6094 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -29,7 +29,7 @@ 4.0.0 - org.wso2.carbon.certificate.mgt.cert.adminapi.feature + org.wso2.carbon.certificate.mgt.cert.admin.api.feature pom WSO2 Carbon - Admin Certificate Management API Feature http://wso2.org @@ -51,7 +51,7 @@ org.wso2.carbon.devicemgt - org.wso2.carbon.certificate.mgt.cert.adminapi + org.wso2.carbon.certificate.mgt.cert.admin.api ${project.version} war @@ -102,7 +102,7 @@ p2-feature-gen - org.wso2.carbon.certificate.mgt.cert.adminapi + org.wso2.carbon.certificate.mgt.cert.admin.api ../../../features/etc/feature.properties diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/build.properties b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/build.properties similarity index 100% rename from features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/build.properties rename to features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/build.properties diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf new file mode 100644 index 00000000000..f88e763ba3b --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf @@ -0,0 +1,2 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/admin-certificate.war,target:${installFolder}/../../deployment/server/webapps/admin-certificate.war,overwrite:true);\ \ No newline at end of file diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf deleted file mode 100644 index ad3dd764037..00000000000 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.adminapi.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,2 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.adminapi_${feature.version}/webapps/admin-certificate.war,target:${installFolder}/../../deployment/server/webapps/admin-certificate.war,overwrite:true);\ \ No newline at end of file diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 026c3d06b18..4ee85993f48 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -37,7 +37,7 @@ org.wso2.carbon.certificate.mgt.server.feature org.wso2.carbon.certificate.mgt.api.feature - org.wso2.carbon.certificate.mgt.cert.adminapi.feature + org.wso2.carbon.certificate.mgt.cert.admin.api.feature From d805245ffc56e5aef37d42815c6e405b3836cc24 Mon Sep 17 00:00:00 2001 From: Madhawa Perera Date: Fri, 27 May 2016 22:15:21 +0530 Subject: [PATCH 03/18] added username field to the device certificate db and related changes --- .../dao/impl/GenericCertificateDAOImpl.java | 27 ++++++++++++------- .../mgt/core/dto/CertificateResponse.java | 11 ++++++++ .../CertificateAuthenticator.java | 5 ++-- .../src/main/resources/dbscripts/cdm/h2.sql | 1 + .../main/resources/dbscripts/cdm/mssql.sql | 1 + .../main/resources/dbscripts/cdm/mysql.sql | 1 + .../main/resources/dbscripts/cdm/oracle.sql | 1 + .../resources/dbscripts/cdm/postgresql.sql | 3 ++- 8 files changed, 37 insertions(+), 13 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index 221000dd40f..73f6ee7b793 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -55,7 +55,11 @@ public class GenericCertificateDAOImpl implements CertificateDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement( - "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID) VALUES (?,?,?)"); + "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME)" + + " VALUES (?,?,?,?)"); + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext. + getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); for (Certificate certificate : certificates) { String serialNumber = certificate.getSerial(); if (serialNumber == null || serialNumber.isEmpty()) { @@ -67,6 +71,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO { stmt.setString(1, serialNumber); stmt.setObject(2, byteArrayInputStream); stmt.setInt(3, certificate.getTenantId()); + stmt.setString(4, username); stmt.addBatch(); } stmt.executeBatch(); @@ -89,8 +94,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO { try { conn = this.getConnection(); String query = - "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" + - " AND TENANT_ID = ? "; + "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM" + + " DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ? AND TENANT_ID = ? "; stmt = conn.prepareStatement(query); stmt.setString(1, serialNumber); stmt.setInt(2, tenantId); @@ -102,6 +107,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO { certificateResponse.setCertificate(certificateBytes); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); break; } @@ -128,8 +134,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO { try { conn = this.getConnection(); String query = - "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER LIKE ?" + - " AND TENANT_ID = ? "; + "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM DM_DEVICE_CERTIFICATE " + + "WHERE SERIAL_NUMBER LIKE ? AND TENANT_ID = ? "; stmt = conn.prepareStatement(query); stmt.setString(1, "%" + serialNumber + "%"); stmt.setInt(2, tenantId); @@ -140,6 +146,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO { byte [] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); } @@ -164,8 +171,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? " + - "ORDER BY ID DESC LIMIT ?,?"; + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, request.getStartIndex()); @@ -178,6 +185,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO { byte [] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); resultCount++; @@ -204,8 +212,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? " + - "ORDER BY ID DESC"; + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME" + + " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); resultSet = stmt.executeQuery(); @@ -215,6 +223,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO { byte [] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java index 9d0504e2dc1..5fc9c82e22c 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java @@ -56,6 +56,17 @@ public class CertificateResponse { @ApiModelProperty(name = "certificateVersion", value = "The version of the certificate", required = true) int certificateVersion; + @ApiModelProperty(name ="username", value="username of the logged user", required = true) + String username; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + public long getNotAfter() { return notAfter; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index 0f9026a3a4a..30313d24992 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -129,10 +129,9 @@ public class CertificateAuthenticator implements WebappAuthenticator { isEmpty()) { authenticationInfo.setTenantId(certificateResponse.getTenantId()); authenticationInfo.setStatus(Status.CONTINUE); - authenticationInfo.setUsername(certificateResponse.getCommonName()); + authenticationInfo.setUsername(certificateResponse.getUsername()); try { - authenticationInfo.setTenantDomain(Utils. - getTenantDomain( + authenticationInfo.setTenantDomain(Utils.getTenantDomain( certificateResponse.getTenantId())); } catch (AuthenticationException e) { authenticationInfo.setStatus(Status.FAILURE); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 22fb0b9d1a3..9afa5b202a9 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index 18036ae943d..e26b1c25c3b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -22,6 +22,7 @@ CREATE TABLE DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE VARBINARY(max) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index f092a99a0d8..3e4366569d5 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) )ENGINE = InnoDB; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index 2cb94d5ed4b..8a64ee59f6c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -50,6 +50,7 @@ CREATE TABLE DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR2(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, TENANT_ID NUMBER(10) DEFAULT 0, + USERNAME VARCHAR2(500) DEFAULT NULL, PRIMARY KEY (ID) ) / diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 957e0f0149c..3f33a64354f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -9,7 +9,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( ID BIGSERIAL NOT NULL PRIMARY KEY, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BYTEA DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0 + TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL ); CREATE TABLE IF NOT EXISTS DM_DEVICE ( From 6328d357972bb2b59e2ba008918b39c93fec480c Mon Sep 17 00:00:00 2001 From: geethkokila Date: Sat, 28 May 2016 00:19:04 +0530 Subject: [PATCH 04/18] Changing the device info object by adding the application list --- .../common/device/details/DeviceWrapper.java | 13 +++++++++ .../core/search/mgt/impl/ProcessorImpl.java | 27 ++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java index 5efdea1b511..47831da5a3b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java @@ -23,6 +23,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; + +import java.util.List; @ApiModel(value = "DeviceWrapper", description = "This contains device details including, " + "location and device meta information.") @@ -38,6 +41,8 @@ public class DeviceWrapper { @ApiModelProperty(name = "deviceLocation", value = "Device's current location", required = true) private DeviceLocation deviceLocation; + private List applications; + public Device getDevice() { return device; } @@ -69,5 +74,13 @@ public class DeviceWrapper { public void setDeviceLocation(DeviceLocation deviceLocation) { this.deviceLocation = deviceLocation; } + + public List getApplications() { + return applications; + } + + public void setApplications(List applications) { + this.applications = applications; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java index 55b377d4f57..275eff3d3aa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -19,8 +19,13 @@ package org.wso2.carbon.device.mgt.core.search.mgt.impl; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.search.mgt.*; import org.wso2.carbon.device.mgt.core.search.mgt.dao.SearchDAO; @@ -35,9 +40,11 @@ import java.util.Map; public class ProcessorImpl implements Processor { private SearchDAO searchDAO; + private ApplicationDAO applicationDAO; public ProcessorImpl() { searchDAO = DeviceManagementDAOFactory.getSearchDAO(); + applicationDAO = DeviceManagementDAOFactory.getApplicationDAO(); } @Override @@ -91,7 +98,9 @@ public class ProcessorImpl implements Processor { deviceWrappers.put(Constants.PROP_OR, this.processORSearch(allORDevices)); deviceWrappers.put(Constants.LOCATION, locationDevices); - return aggregator.aggregate(deviceWrappers); + List finalDeviceWrappers = aggregator.aggregate(deviceWrappers); + this.setApplicationListOfDevices(finalDeviceWrappers); + return finalDeviceWrappers; } @Override @@ -186,5 +195,21 @@ public class ProcessorImpl implements Processor { return maps; } + + private void setApplicationListOfDevices(List deviceWrappers) throws SearchMgtException { + try { + DeviceManagementDAOFactory.openConnection(); + for (DeviceWrapper wrapper : deviceWrappers) { + wrapper.setApplications(applicationDAO.getInstalledApplications(wrapper.getDevice().getId())); + } + } catch (DeviceManagementDAOException e) { + throw new SearchMgtException("Error occurred while fetching the Application List of devices ", e); + } catch (SQLException e) { + throw new SearchMgtException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + } From f4f47cbfddb5aaadfde0a3a7106acce8fbad5975 Mon Sep 17 00:00:00 2001 From: dilanua Date: Sat, 28 May 2016 00:41:21 +0530 Subject: [PATCH 05/18] Changing view names to fix oracle naming issues in dashboard analytics feature --- .../dashboard/dao/GadgetDataServiceDAOConstants.java | 4 ++-- .../src/main/resources/dbscripts/cdm/h2.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/mssql.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/mysql.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/postgresql.sql | 4 ++-- pom.xml | 3 +-- 6 files changed, 11 insertions(+), 12 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java index bbaf5d657ae..cd770b96514 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java @@ -22,8 +22,8 @@ public final class GadgetDataServiceDAOConstants { public static class DatabaseView { - public static final String DEVICES_VIEW_1 = "DEVICES_WITH_POLICY_COMPLIANCE_STATUS"; - public static final String DEVICES_VIEW_2 = "DEVICES_WITH_NON_COMPLIANT_FEATURES"; + public static final String DEVICES_VIEW_1 = "POLICY_COMPLIANCE_INFO"; + public static final String DEVICES_VIEW_2 = "FEATURE_NON_COMPLIANCE_INFO"; private DatabaseView() { throw new AssertionError(); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 20c9343a6ad..dbbcd4e0923 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -516,7 +516,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( -- DASHBOARD RELATED VIEWS -- -CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS +CREATE VIEW POLICY_COMPLIANCE_INFO AS SELECT DEVICE_INFO.DEVICE_ID, DEVICE_INFO.DEVICE_IDENTIFICATION, @@ -545,7 +545,7 @@ FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID ORDER BY DEVICE_INFO.DEVICE_ID; -CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS +CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS SELECT DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.DEVICE_IDENTIFICATION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index 466306b3e36..f90b4eae79f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -508,7 +508,7 @@ CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC) -- DASHBOARD RELATED VIEWS -- -CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS +CREATE VIEW POLICY_COMPLIANCE_INFO AS SELECT TOP 100 PERCENT DEVICE_INFO.DEVICE_ID, DEVICE_INFO.DEVICE_IDENTIFICATION, @@ -540,7 +540,7 @@ ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID ORDER BY DEVICE_INFO.DEVICE_ID; GO -CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS +CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS SELECT TOP 100 PERCENT DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.DEVICE_IDENTIFICATION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 08f97b1091a..d3be894e74f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -546,7 +546,7 @@ POLICY_ID, STATUS AS IS_COMPLIANT FROM DM_POLICY_COMPLIANCE_STATUS; -CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS +CREATE VIEW POLICY_COMPLIANCE_INFO AS SELECT DEVICE_INFO_VIEW.DEVICE_ID, DEVICE_INFO_VIEW.DEVICE_IDENTIFICATION, @@ -563,7 +563,7 @@ DEVICE_WITH_POLICY_INFO_VIEW ON DEVICE_INFO_VIEW.DEVICE_ID = DEVICE_WITH_POLICY_INFO_VIEW.DEVICE_ID ORDER BY DEVICE_INFO_VIEW.DEVICE_ID; -CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS +CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS SELECT DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.DEVICE_IDENTIFICATION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index cf08d57cbf8..51dac1c6c10 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -435,7 +435,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( -- DASHBOARD RELATED VIEWS -- -CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS +CREATE VIEW POLICY_COMPLIANCE_INFO AS SELECT DEVICE_INFO.DEVICE_ID, DEVICE_INFO.DEVICE_IDENTIFICATION, @@ -464,7 +464,7 @@ FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID ORDER BY DEVICE_INFO.DEVICE_ID; -CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS +CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS SELECT DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.DEVICE_IDENTIFICATION, diff --git a/pom.xml b/pom.xml index 1ac139acd58..d5708f77d70 100644 --- a/pom.xml +++ b/pom.xml @@ -52,7 +52,7 @@ features/oauth-extensions features/email-sender features/jwt-client - features/device-mgt-extensions + features/device-mgt-extensions @@ -1721,7 +1721,6 @@ - 6.1.1 4.4.3 From 02217825335983418030ef316be56803d7cecf37 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Sat, 28 May 2016 01:57:36 +0530 Subject: [PATCH 06/18] Adding new apis for getting the device location when list of device identifiers are supplied --- .../mgt/jaxrs/api/DeviceInformation.java | 20 ++++++++++++++++ .../jaxrs/api/impl/DeviceInformationImpl.java | 17 ++++++++++++++ .../details/mgt/DeviceInformationManager.java | 8 +++++++ .../impl/DeviceInformationManagerImpl.java | 23 ++++++++++++++++++- 4 files changed, 67 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java index b10412b516a..355806ee9db 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java @@ -105,4 +105,24 @@ public interface DeviceInformation { @ApiParam(name = "id", value = "Provide the device identifier", required = true) @PathParam("id") String id); + + @GET + @Path("location/list") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get the locations of devices", + notes = "This will return the locations of devices including latitude and longitude as well the " + + "physical address for the supplied device identifiers", + response = DeviceLocation.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) + Response getDeviceLocations(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers", + required = true) List deviceIdentifiers); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java index a59c81be542..3bbc90d4f4b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.jaxrs.api.impl; +import io.swagger.annotations.ApiParam; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -96,5 +97,21 @@ public class DeviceInformationImpl implements DeviceInformation { } return Response.status(Response.Status.OK).entity(deviceLocation).build(); } + + @Override + public Response getDeviceLocations(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers", + required = true) List deviceIdentifiers) { + DeviceInformationManager informationManager; + List deviceLocations; + try { + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); + deviceLocations = informationManager.getDeviceLocations(deviceIdentifiers); + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while getting the device location."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(deviceLocations).build(); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java index 5b62a0f8dd2..1c947b63728 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java @@ -72,6 +72,14 @@ public interface DeviceInformationManager { */ DeviceLocation getDeviceLocation(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException; + /** + * This method will return the device location with latitude, longitude, address etc.. of supplied devices. + * @param deviceIdentifiers - List of Device identifier and device type. + * @return Device Location list. + * @throws DeviceDetailsMgtException + */ + List getDeviceLocations(List deviceIdentifiers) throws DeviceDetailsMgtException; + // /** // * This method will manage the storing of device application list. // * @param deviceApplication - Device application list. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index b2266d35cd8..96f8addaae5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -121,7 +121,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } } DeviceManagementDAOFactory.openConnection(); - for(Integer id : deviceIds) { + for (Integer id : deviceIds) { DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(id); deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(id)); deviceInfos.add(deviceInfo); @@ -183,5 +183,26 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } } + @Override + public List getDeviceLocations(List deviceIdentifiers) throws DeviceDetailsMgtException { + + try { + List devices = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider().getAllDevices(deviceIdentifiers.get(0).getType()); + List deviceLocations = new ArrayList<>(); + DeviceManagementDAOFactory.openConnection(); + for (Device device : devices) { + deviceLocations.add(deviceDetailsDAO.getDeviceLocation(device.getId())); + } + return deviceLocations; + } catch (DeviceManagementException e) { + throw new DeviceDetailsMgtException("Exception occurred while retrieving the devices.", e); + } catch (SQLException e) { + throw new DeviceDetailsMgtException("SQL error occurred while retrieving device from database.", e); + } catch (DeviceDetailsMgtDAOException e) { + throw new DeviceDetailsMgtException("Exception occurred while retrieving device locations.", e); + } + } + } From ecc8b5e6f2bd59b6c34e33ea8017cf99ff4dcba5 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Sat, 28 May 2016 02:02:43 +0530 Subject: [PATCH 07/18] Fixing the api issues --- .../wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java | 3 ++- .../device/mgt/jaxrs/api/impl/DeviceInformationImpl.java | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java index 355806ee9db..84883a97c31 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java @@ -114,7 +114,8 @@ public interface DeviceInformation { value = "Get the locations of devices", notes = "This will return the locations of devices including latitude and longitude as well the " + "physical address for the supplied device identifiers", - response = DeviceLocation.class) + response = DeviceLocation.class, + responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = ""), @ApiResponse(code = 400, message = ""), diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java index 3bbc90d4f4b..b77799393fb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java @@ -99,6 +99,7 @@ public class DeviceInformationImpl implements DeviceInformation { } @Override + @Path("location/list") public Response getDeviceLocations(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers", required = true) List deviceIdentifiers) { DeviceInformationManager informationManager; From ed0da9e1d07576bf5e000a8daeca4bde0cd0f0f1 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Sat, 28 May 2016 03:12:10 +0530 Subject: [PATCH 08/18] Fixing the device informations to get the applications --- .../mgt/jaxrs/api/DeviceInformation.java | 23 +++++++++++++++++++ .../jaxrs/api/impl/DeviceInformationImpl.java | 22 ++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java index 84883a97c31..98193a3b6ee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.jaxrs.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.*; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; @@ -126,4 +127,26 @@ public interface DeviceInformation { Response getDeviceLocations(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers", required = true) List deviceIdentifiers); + + @GET + @Path("application/{type}/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get the device applications", + notes = "This will return the device applications including their memory usages.", + response = Application.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) + Response getDeviceApplications(@ApiParam(name = "type", value = "Provide the device type, such as ios, " + + "android or windows", required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Provide the device identifier", + required = true) @PathParam("id") String id); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java index b77799393fb..0284b383c9c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java @@ -23,8 +23,11 @@ import io.swagger.annotations.ApiParam; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.jaxrs.api.DeviceInformation; @@ -114,5 +117,24 @@ public class DeviceInformationImpl implements DeviceInformation { } return Response.status(Response.Status.OK).entity(deviceLocations).build(); } + + @Override + @Path("application/{type}/{id}") + public Response getDeviceApplications(@PathParam("type") String type, @PathParam("id") String id) { + List applications; + ApplicationManagementProviderService applicationManagementProviderService; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + try { + deviceIdentifier.setType(type); + deviceIdentifier.setId(id); + applicationManagementProviderService = DeviceMgtAPIUtils.getAppManagementService(); + applications = applicationManagementProviderService.getApplicationListForDevice(deviceIdentifier); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while fetching the apps of the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(applications).build(); + } } From 20343d93497d15020e2781d6266c074d05438875 Mon Sep 17 00:00:00 2001 From: hasuniea Date: Mon, 30 May 2016 13:03:21 +0530 Subject: [PATCH 09/18] fixed swagger message issue --- .../wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java | 2 +- .../device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java index c2c5c99f81b..5a02dc08371 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java @@ -112,7 +112,7 @@ public interface DeviceNotification { value = "Sending a Device Notification", notes = "Notify users on device operation failures and other information using this REST API") @ApiResponses(value = { - @ApiResponse(code = 201, message = "NNotification has added successfully"), + @ApiResponse(code = 201, message = "Notification has been added successfully"), @ApiResponse(code = 500, message = "Error occurred while updating notification status") }) @Permission(scope = "device-notification-modify", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java index 3a4ece1a171..ea2da30f29e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java @@ -97,7 +97,7 @@ public class DeviceNotificationImpl implements DeviceNotification{ ResponsePayload responseMsg = new ResponsePayload(); try { DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification); - responseMsg.setMessageFromServer("Notification has added successfully."); + responseMsg.setMessageFromServer("Notification has been added successfully."); responseMsg.setStatusCode(HttpStatus.SC_CREATED); return Response.status(Response.Status.CREATED).entity(responseMsg).build(); } catch (NotificationManagementException e) { From 5ed982beb4c2971741ad8f8e27821a0700996b15 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 30 May 2016 16:40:57 +0530 Subject: [PATCH 10/18] Adding more improvements to the JAX-RS APIs of CDM-F --- .../api/ConfigurationManagementService.java | 12 +-- .../service/api/DeviceManagementService.java | 63 ++++++++-------- .../impl/ConfigurationServiceImpl.java | 8 +- .../impl/DeviceManagementServiceImpl.java | 49 ++++++++---- .../mgt/jaxrs/util/DeviceMgtAPIUtils.java | 2 +- .../IllegalTransactionStateException.java | 1 - .../UnAuthorizedDeviceAccessException.java | 45 +++++++++++ ...ApplicationManagerProviderServiceImpl.java | 7 ++ .../mgt/dao/impl/DeviceDetailsDAOImpl.java | 9 +-- .../impl/DeviceInformationManagerImpl.java | 49 ++++++++---- .../operation/mgt/OperationManagerImpl.java | 74 +++++++++---------- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 23 ++++-- .../mgt/core/util/PolicyManagerUtil.java | 2 +- 13 files changed, 222 insertions(+), 122 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java index 3dae98bf7f0..ab067e0e197 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java @@ -22,6 +22,7 @@ import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -45,7 +46,6 @@ public interface ConfigurationManagementService { httpMethod = "GET", value = "Get the general platform configurations.", notes = "Get the general platform level configuration details.", - response = PlatformConfiguration.class, tags = "Configuration Management") @ApiResponses(value = { @ApiResponse( @@ -74,7 +74,9 @@ public interface ConfigurationManagementService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the general platform configuration.") + message = "Internal Server ErrorResponse. \n Server error occurred while fetching the general " + + "platform configuration.", + response = ErrorResponse.class) }) @Permission(scope = "configuration-view", permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"}) @@ -115,16 +117,14 @@ public interface ConfigurationManagementService { @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 404, - message = "Not Found. \n Resource to be deleted does not exist."), @ApiResponse( code = 415, message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while modifying general platform configuration.") + "Server error occurred while modifying general platform configuration.", + response = ErrorResponse.class) }) @Permission(scope = "configuration-modify", permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"}) 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 7e12f306e7e..46708a16e73 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 @@ -30,12 +30,12 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.policy.mgt.common.Policy; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.Date; import java.util.List; /** @@ -138,7 +138,6 @@ public interface DeviceManagementService { value = "Retrieve devices information from the supplied device identifier.", notes = "This will return device information such as CPU usage, memory usage etc for supplied device " + "identifier.", - response = DeviceInfo.class, tags = "Device Management") @ApiResponses( value = { @@ -172,13 +171,17 @@ public interface DeviceManagementService { @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id."), @ApiResponse( code = 406, message = "Not Acceptable. \n The requested media type is not supported."), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while retrieving information of the list of the devices submitted.") + "Server error occurred while retrieving information of the list of the devices submitted.", + response = ErrorResponse.class) }) @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) Response getDeviceInfo( @@ -270,7 +273,6 @@ public interface DeviceManagementService { httpMethod = "GET", value = "Get information of the requested device.", notes = "Returns information of the requested device.", - response = Device.class, tags = "Device Management") @ApiResponses( value = { @@ -301,7 +303,8 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while retrieving information requested device.") + "Server error occurred while retrieving information requested device.", + response = ErrorResponse.class) }) @Permission(scope = "device-view", permissions = { "/permission/admin/device-mgt/admin/devices/view", @@ -332,7 +335,6 @@ public interface DeviceManagementService { value = "Get the device location of a given device and a device type.", notes = "This will return the device location including latitude and longitude as well the " + "physical address.", - response = DeviceLocation.class, tags = "Device Management") @ApiResponses( value = { @@ -346,10 +348,11 @@ public interface DeviceManagementService { "Empty body because the client already has the latest version of the requested resource."), @ApiResponse( code = 404, - message = "Location details are not available for the given device."), + message = "Not Found. \n No device is found under the provided type and id."), @ApiResponse( code = 500, - message = "ErrorResponse occurred while getting the device location.") + message = "ErrorResponse occurred while getting the device location.", + response = ErrorResponse.class) }) @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) Response getDeviceLocation( @@ -379,8 +382,6 @@ public interface DeviceManagementService { value = "Get the device location of a given devices and a device type.", notes = "This will return the device locations including latitude and longitude as well the " + "physical address of the given devices.", - response = DeviceLocation.class, - responseContainer = "List", tags = "Device Management") @ApiResponses( value = { @@ -398,7 +399,8 @@ public interface DeviceManagementService { message = "Location details are not available for the given devices."), @ApiResponse( code = 500, - message = "ErrorResponse occurred while getting the device location.") + message = "ErrorResponse occurred while getting the device location.", + response = ErrorResponse.class) }) @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) Response getDeviceLocations( @@ -422,8 +424,6 @@ public interface DeviceManagementService { notes = "WSO2 EMM features enable you to carry out many operations on a given device platform. " + "Using this REST API you can get the features that can be carried out on a preferred device type," + " such as iOS, Android or Windows.", - response = Feature.class, - responseContainer = "List", tags = "Device Management") @ApiResponses( value = { @@ -458,7 +458,8 @@ public interface DeviceManagementService { "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."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Device of which the feature list is requested, is not found."), @@ -468,7 +469,8 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while retrieving feature list of the device.") + "Server error occurred while retrieving feature list of the device.", + response = ErrorResponse.class) }) @Permission(scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/view", "/permission/admin/device-mgt/user/devices/view"}) @@ -497,8 +499,6 @@ public interface DeviceManagementService { httpMethod = "POST", value = "Advanced search for devices.", notes = "Carry out an advanced search of devices.", - response = DeviceWrapper.class, - responseContainer = "List", tags = "Device Management") @ApiResponses( value = { @@ -526,7 +526,8 @@ public interface DeviceManagementService { "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."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 406, message = "Not Acceptable.\n The requested media type is not supported"), @@ -536,7 +537,8 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while enrolling the device.") + "Server error occurred while enrolling the device.", + response = ErrorResponse.class) }) @Permission(scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) Response searchDevices( @@ -562,9 +564,7 @@ public interface DeviceManagementService { produces = MediaType.APPLICATION_JSON, httpMethod = "GET", value = "Getting installed application details of a device.", - responseContainer = "List", notes = "Get the list of applications that a device has subscribed.", - response = Application.class, tags = "Device Management") @ApiResponses( value = { @@ -599,7 +599,8 @@ public interface DeviceManagementService { "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."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Device of which the application list is requested, is not found."), @@ -609,7 +610,8 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while retrieving installed application list of the device.") + "Server error occurred while retrieving installed application list of the device.", + response = ErrorResponse.class) }) @Permission(scope = "operation-view", permissions = { "/permission/admin/device-mgt/admin/devices/view", @@ -651,8 +653,6 @@ public interface DeviceManagementService { notes = "You will carry out many operations on a device. In a situation where you wish to view the all" + " the operations carried out on a device it is not feasible to show all the details on one page" + " therefore the details are paginated.", - response = Operation.class, - responseContainer = "List", tags = "Device Management") @ApiResponses( value = { @@ -687,7 +687,8 @@ public interface DeviceManagementService { "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."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Device of which the operation list is requested, is not found."), @@ -697,7 +698,8 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while retrieving operation list scheduled for the device.") + "Server error occurred while retrieving operation list scheduled for the device.", + response = ErrorResponse.class) }) @Permission(scope = "operation-view", permissions = { "/permission/admin/device-mgt/admin/devices/view", @@ -739,7 +741,6 @@ public interface DeviceManagementService { notes = "When a device registers with WSO2 EMM a policy is enforced on the device. Initially the EMM " + "filters the policies based on the Platform (device type), filters based on the device ownership" + " type , filters based on the user role or name and finally the policy is enforced on the device.", - response = Policy.class, tags = "Device Management") @ApiResponses( value = { @@ -773,7 +774,8 @@ public interface DeviceManagementService { "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."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Device of which the effective policy is requested, is not found."), @@ -783,7 +785,8 @@ public interface DeviceManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while retrieving the effective policy calculated for the device.") + "Server error occurred while retrieving the effective policy calculated for the device.", + response = ErrorResponse.class) }) Response getEffectivePolicyOfDevice( @ApiParam( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java index 177f87c9d08..4a2126f6aae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java @@ -23,7 +23,9 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.ConfigurationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.MDMAppConstants; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; @@ -63,7 +65,8 @@ public class ConfigurationServiceImpl implements ConfigurationManagementService } catch (ConfigurationManagementException | PolicyManagementException e) { msg = "ErrorResponse occurred while retrieving the configurations."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -80,7 +83,8 @@ public class ConfigurationServiceImpl implements ConfigurationManagementService } catch (ConfigurationManagementException e) { String msg = "ErrorResponse occurred while updating the configuration."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } 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 81f5bedb3cb..75e886cb92d 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 @@ -36,8 +36,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; 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.DeviceManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; @@ -98,7 +100,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (DeviceManagementException e) { String msg = "Error occurred while fetching all enrolled devices"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -116,10 +119,15 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { deviceIdentifier.setType(type); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); + if (deviceInfo == null) { + return Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is " + + "found upon the give type '" + type + "' and id '" + id + "'").build(); + } } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device information."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(deviceInfo).build(); } @@ -162,7 +170,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (DeviceManagementException e) { String msg = "Error occurred while fetching the device information."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } if (device == null) { return Response.status(Response.Status.NOT_FOUND).entity("Requested device of type '" + type + @@ -194,7 +203,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String msg = "Error occurred while getting the last updated location of the '" + type + "' device, " + "which carries the id '" + id + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(deviceLocation).build(); } @@ -211,7 +221,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device location."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(deviceLocations).build(); } @@ -229,16 +240,18 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { RequestValidationUtil.validateDeviceIdentifier(type, id); dms = DeviceMgtAPIUtils.getDeviceManagementService(); - features = dms.getFeatureManager(type).getFeatures(); + FeatureManager fm = dms.getFeatureManager(type); + if (fm == null) { + return Response.status(Response.Status.NOT_FOUND).entity("No feature manager is registered with " + + "the given type '" + type + "'").build(); + } + features = fm.getFeatures(); } catch (DeviceManagementException e) { String msg = "Error occurred while retrieving the list of features of '" + type + "' device, which " + "carries the id '" + id + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - if (features == null) { - return Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is found upon " + - "the provided type and id").build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(features).build(); } @@ -256,7 +269,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (SearchMgtException e) { String msg = "Error occurred while searching for devices that matches the provided selection criteria"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } if (devices == null) { return Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is found upon " + @@ -283,13 +297,14 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { applications = amc.getApplicationListForDevice(new DeviceIdentifier(id, type)); if (applications == null) { return Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is found upon" + - "the provided type and id").build(); + " the provided type and id").build(); } } catch (ApplicationManagementException e) { String msg = "Error occurred while fetching the apps of the '" + type + "' device, which carries " + "the id '" + id + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(applications).build(); } @@ -318,7 +333,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String msg = "Error occurred while fetching the operations for the '" + type + "' device, which " + "carries the id '" + id + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(operations).build(); } @@ -343,7 +359,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String msg = "Error occurred while retrieving the current policy associated with the '" + type + "' device, which carries the id '" + id + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index 53ec73b8418..dfb8bc19dfa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -71,7 +71,7 @@ public class DeviceMgtAPIUtils { "frequency.").build() ); } - return Integer.parseInt(entry.getValue().toString()); + return (int) (Double.parseDouble(entry.getValue().toString()) + 0.5d); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java index 3d007fbf77e..1cc0594ba7d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java @@ -42,5 +42,4 @@ public class IllegalTransactionStateException extends RuntimeException { super(cause); } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java new file mode 100644 index 00000000000..7a1846001cc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.common; + +public class UnauthorizedDeviceAccessException extends RuntimeException { + + private static final long serialVersionUID = -3151289331929070297L; + + public UnauthorizedDeviceAccessException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public UnauthorizedDeviceAccessException(String message, Throwable cause) { + super(message, cause); + } + + public UnauthorizedDeviceAccessException(String msg) { + super(msg); + } + + public UnauthorizedDeviceAccessException() { + super(); + } + + public UnauthorizedDeviceAccessException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index 61eb2669fee..a33df19a415 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -264,6 +264,13 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceManagementDAOFactory.openConnection(); device = deviceDAO.getDevice(deviceId, tenantId); + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the device identifier '" + deviceId.getId() + + "' and type '" + deviceId.getType() + "'. Therefore returning null"); + } + return null; + } return applicationDAO.getInstalledApplications(device.getId()); } catch (DeviceManagementDAOException e) { throw new ApplicationManagementException("Error occurred while fetching the Application List of '" + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index 3b392cc8200..c951f13944e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -112,20 +112,20 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { @Override public DeviceInfo getDeviceInformation(int deviceId) throws DeviceDetailsMgtDAOException { - Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - DeviceInfo deviceInfo = new DeviceInfo(); + DeviceInfo deviceInfo = null; try { conn = this.getConnection(); - String sql = "SELECT * FROM DM_DEVICE_DETAIL WHERE DEVICE_ID = ?"; + String sql = "SELECT * FROM DM_DEVICE_DETAIL WHERE DEVICE_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); rs = stmt.executeQuery(); - while (rs.next()) { + if (rs.next()) { + deviceInfo = new DeviceInfo(); deviceInfo.setDeviceId(rs.getInt("DEVICE_ID")); // deviceInfo.setIMEI(rs.getString("IMEI")); // deviceInfo.setIMSI(rs.getString("IMSI")); @@ -148,7 +148,6 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); } - deviceInfo.setDeviceId(deviceId); return deviceInfo; } catch (SQLException e) { throw new DeviceDetailsMgtDAOException("Error occurred while fetching the details of the registered devices.", e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index e1033cc3ee0..0532f21ddaa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -19,6 +19,8 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; @@ -38,6 +40,7 @@ import java.util.Map; public class DeviceInformationManagerImpl implements DeviceInformationManager { private DeviceDetailsDAO deviceDetailsDAO; + private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class); public DeviceInformationManagerImpl() { this.deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); @@ -72,13 +75,22 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } @Override - public DeviceInfo getDeviceInfo( - DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException { - + public DeviceInfo getDeviceInfo(DeviceIdentifier deviceId) throws DeviceDetailsMgtException { + Device device; + try { + device = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider().getDevice(deviceId); + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the device identifier '" + deviceId.getId() + + "' and type '" + deviceId.getType() + "'. Therefore returning null"); + } + return null; + } + } catch (DeviceManagementException e) { + throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e); + } try { - Device device = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getDevice(deviceIdentifier); - DeviceManagementDAOFactory.openConnection(); DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId()); deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(device.getId())); @@ -86,8 +98,6 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } catch (SQLException e) { throw new DeviceDetailsMgtException("SQL error occurred while retrieving device from database.", e); - } catch (DeviceManagementException e) { - throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e); } catch (DeviceDetailsMgtDAOException e) { throw new DeviceDetailsMgtException("Exception occurred while retrieving device details.", e); } finally { @@ -114,7 +124,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } } DeviceManagementDAOFactory.openConnection(); - for(Integer id : deviceIds) { + for (Integer id : deviceIds) { DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(id); deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(id)); deviceInfos.add(deviceInfo); @@ -157,18 +167,25 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } @Override - public DeviceLocation getDeviceLocation(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException { + public DeviceLocation getDeviceLocation(DeviceIdentifier deviceId) throws DeviceDetailsMgtException { + Device device; + try { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the device identifier '" + deviceId.getId() + + "' and type '" + deviceId.getType() + "'. Therefore returning null"); + } + return null; + } + } catch (DeviceManagementException e) { + throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e); + } try { - Device device = DeviceManagementDataHolder.getInstance(). - getDeviceManagementProvider().getDevice(deviceIdentifier); - DeviceManagementDAOFactory.openConnection(); return deviceDetailsDAO.getDeviceLocation(device.getId()); - } catch (SQLException e) { throw new DeviceDetailsMgtException("SQL error occurred while retrieving device from database.", e); - } catch (DeviceManagementException e) { - throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e); } catch (DeviceDetailsMgtDAOException e) { throw new DeviceDetailsMgtException("Exception occurred while retrieving device location.", e); } finally { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index c4bb97bc229..3d60f9f78a7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -185,49 +185,49 @@ public class OperationManagerImpl implements OperationManager { } @Override - public List getOperations( - DeviceIdentifier deviceId) throws OperationManagementException { + public List getOperations(DeviceIdentifier deviceId) throws OperationManagementException { int enrolmentId; - List operations = new ArrayList<>(); + List operations = null; try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { + if (!isUserAuthorized) { + throw new UnauthorizedDeviceAccessException("User '" + getUser() + "' is not authorized to " + + "fetch operations on device '" + deviceId.getId() + "'"); + } + try { try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - if (enrolmentId < 0) { - return null; - } - OperationManagementDAOFactory.openConnection(); - List operationList = - operationDAO.getOperationsForDevice(enrolmentId); - - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { - Operation operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); - } - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving metadata of '" + - deviceId.getType() + "' device carrying the identifier '" + - deviceId.getId() + "'"); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); } finally { - OperationManagementDAOFactory.closeConnection(); + DeviceManagementDAOFactory.closeConnection(); } - } else { - log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); + if (enrolmentId < 0) { + return null; + } + OperationManagementDAOFactory.openConnection(); + List operationList = + operationDAO.getOperationsForDevice(enrolmentId); + + operations = new ArrayList<>(); + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { + Operation operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving metadata of '" + + deviceId.getType() + "' device carrying the identifier '" + + deviceId.getId() + "'"); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + @@ -757,7 +757,7 @@ public class OperationManagerImpl implements OperationManager { // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. int operationId = Integer.parseInt( activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); - if (operationId == 0){ + if (operationId == 0) { throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); } try { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 45258a58510..778de88dad0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -607,7 +607,7 @@ public class PolicyManagerImpl implements PolicyManager { policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId())); List deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId()); - if(!deviceGroupWrappers.isEmpty()){ + if (!deviceGroupWrappers.isEmpty()) { deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers); } policy.setDeviceGroups(deviceGroupWrappers); @@ -977,17 +977,26 @@ public class PolicyManagerImpl implements PolicyManager { } @Override - public Policy getAppliedPolicyToDevice( - DeviceIdentifier deviceIdentifier) throws PolicyManagementException { + public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException { Policy policy; + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + Device device; + try { + device = service.getDevice(deviceId); + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the device identifier '" + deviceId.getId() + + "' and type '" + deviceId.getType() + "'. Therefore returning null"); + } + return null; + } + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting device id.", e); + } try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier); //int policyId = policyDAO.getAppliedPolicyId(device.getId()); PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getAppliedPolicy(device.getId(), device.getEnrolmentInfo().getId()); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while getting device id.", e); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting policy id or policy.", e); } catch (SQLException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index b233ed85528..c05700009d0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -212,7 +212,7 @@ public class PolicyManagerUtil { throw new PolicyManagementException("Invalid value, i.e. '" + cEntry.getValue() + "', is configured as the monitoring frequency"); } - monitoringFrequency = Integer.parseInt(cEntry.getValue().toString()); + monitoringFrequency = (int) (Double.parseDouble(cEntry.getValue().toString()) + 0.5d); } } } From af58e5ec880bb56c8a0d2f3a3b48c4178e8d7c3a Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 30 May 2016 16:42:10 +0530 Subject: [PATCH 11/18] Code cleanup --- .../mgt/core/operation/mgt/OperationManagerImpl.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 3d60f9f78a7..7535349ca23 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -762,9 +762,7 @@ public class OperationManagerImpl implements OperationManager { } try { OperationManagementDAOFactory.openConnection(); - Activity act = operationDAO.getActivity(operationId); -// act.setActivityId(activity); - return act; + return operationDAO.getActivity(operationId); } catch (SQLException e) { throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); } catch (OperationManagementDAOException e) { @@ -850,8 +848,4 @@ public class OperationManagerImpl implements OperationManager { return status; } - private void setActivityId(Operation operation, int enrolmentId) { - operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + enrolmentId); - } - } From 9c3c08b4caa6fc57efba8ac0f0e96162e8bbdc56 Mon Sep 17 00:00:00 2001 From: hasuniea Date: Mon, 30 May 2016 17:15:21 +0530 Subject: [PATCH 12/18] fix UnAuthorizedDeviceAccessException.java --- ...ssException.java => UnauthorizedDeviceAccessException.java} | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/{UnAuthorizedDeviceAccessException.java => UnauthorizedDeviceAccessException.java} (99%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnauthorizedDeviceAccessException.java similarity index 99% rename from components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnauthorizedDeviceAccessException.java index 7a1846001cc..2f35d878f2c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnAuthorizedDeviceAccessException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/UnauthorizedDeviceAccessException.java @@ -16,10 +16,10 @@ * under the License. * */ + package org.wso2.carbon.device.mgt.common; public class UnauthorizedDeviceAccessException extends RuntimeException { - private static final long serialVersionUID = -3151289331929070297L; public UnauthorizedDeviceAccessException(String msg, Exception nestedEx) { @@ -41,5 +41,4 @@ public class UnauthorizedDeviceAccessException extends RuntimeException { public UnauthorizedDeviceAccessException(Throwable cause) { super(cause); } - } From 20fd2ec7680cfa0f009e3b023e74a9b8e4bf9ef7 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 30 May 2016 17:46:37 +0530 Subject: [PATCH 13/18] Improving application installation/uninstallation handling --- .../device/mgt/jaxrs/beans/ActivityList.java | 1 - .../ApplicationManagementAdminService.java | 21 ++++--- ...ApplicationManagementAdminServiceImpl.java | 56 +++++++++++++++---- .../impl/util/RequestValidationUtil.java | 39 +++++++++++++ 4 files changed, 97 insertions(+), 20 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java index 68240514ee5..18eb30c080d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java @@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import java.util.ArrayList; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java index df5c1220435..c7e2c1a26aa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import javax.ws.rs.Consumes; import javax.ws.rs.POST; @@ -50,11 +51,12 @@ public interface ApplicationManagementAdminService { tags = "Application Management Administrative Service") @ApiResponses(value = { @ApiResponse( - code = 200, - message = "OK. \n Install application operations have been successfully scheduled upon given devices"), + code = 202, + message = "OK. \n Install application operation will be delivered to the given devices"), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Resource to be processed does not exist."), @@ -65,7 +67,8 @@ public interface ApplicationManagementAdminService { code = 500, message = "Internal Server ErrorResponse. \n " + "Server error occurred while bulk issuing application installation operations upon " + - "a given set of devices.") + "a given set of devices.", + response = ErrorResponse.class) }) Response installApplication( @ApiParam( @@ -84,11 +87,12 @@ public interface ApplicationManagementAdminService { tags = "Application Management Administrative Service") @ApiResponses(value = { @ApiResponse( - code = 200, - message = "OK. \n Uninstall application operations have been successfully scheduled upon given devices"), + code = 202, + message = "OK. \n Uninstall application operation will be delivered to the provided devices"), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Resource to be processed does not exist."), @@ -99,7 +103,8 @@ public interface ApplicationManagementAdminService { code = 500, message = "Internal Server ErrorResponse. \n " + "Server error occurred while bulk issuing application un-installation operations upon " + - "a given set of devices.") + "a given set of devices.", + response = ErrorResponse.class) }) Response uninstallApplication( @ApiParam( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java index 51d17a9770d..e669c73dcbc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java @@ -25,8 +25,12 @@ import org.wso2.carbon.device.mgt.common.Platform; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.exception.UnknownApplicationTypeException; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.ApplicationManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.MDMAndroidOperationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.MDMIOSOperationUtil; @@ -53,30 +57,45 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem public Response installApplication(ApplicationWrapper applicationWrapper) { ApplicationManager appManagerConnector; Operation operation = null; + + RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper); try { appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); MobileApp mobileApp = applicationWrapper.getApplication(); if (applicationWrapper.getDeviceIdentifiers() != null) { for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { - if (deviceIdentifier.getType().equals(Platform.ANDROID.toString())) { + if (Platform.ANDROID.toString().equals(deviceIdentifier.getType())) { operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp); - } else if (deviceIdentifier.getType().equals(Platform.IOS.toString())) { + } else if (Platform.IOS.toString().equals(deviceIdentifier.getType())) { operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp); } } - appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + if (applicationWrapper.getRoleNameList() != null && applicationWrapper.getRoleNameList().size() > 0) { + appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList()); + } else if (applicationWrapper.getUserNameList() != null && + applicationWrapper.getUserNameList().size() > 0) { + appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList()); + } else if (applicationWrapper.getDeviceIdentifiers() != null && + applicationWrapper.getDeviceIdentifiers().size() > 0) { + appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + } else { + throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + "No application installation criteria i.e. user/role/device is given").build()); + } } return Response.status(Response.Status.ACCEPTED).entity("Application installation request has been sent " + - "to the device").build(); + "to the device(s)").build(); } catch (ApplicationManagementException e) { String msg = "ErrorResponse occurred while processing application installation request"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } catch (UnknownApplicationTypeException e) { String msg = "The type of application requested to be installed is not supported"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -86,30 +105,45 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem public Response uninstallApplication(ApplicationWrapper applicationWrapper) { ApplicationManager appManagerConnector; org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; + + RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper); try { appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); MobileApp mobileApp = applicationWrapper.getApplication(); if (applicationWrapper.getDeviceIdentifiers() != null) { for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { - if (deviceIdentifier.getType().equals(Platform.ANDROID.toString())) { + if (Platform.ANDROID.toString().equals(deviceIdentifier.getType())) { operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp); } else if (deviceIdentifier.getType().equals(Platform.IOS.toString())) { operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp); } } - appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + if (applicationWrapper.getRoleNameList() != null && applicationWrapper.getRoleNameList().size() > 0) { + appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList()); + } else if (applicationWrapper.getUserNameList() != null && + applicationWrapper.getUserNameList().size() > 0) { + appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList()); + } else if (applicationWrapper.getDeviceIdentifiers() != null && + applicationWrapper.getDeviceIdentifiers().size() > 0) { + appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + } else { + throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + "No application un-installation criteria i.e. user/role/device is given").build()); + } } return Response.status(Response.Status.ACCEPTED).entity("Application un-installation request has " + - "been sent to the device").build(); + "been sent to the given device(s)").build(); } catch (ApplicationManagementException e) { String msg = "ErrorResponse occurred while processing application un-installation request"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } catch (UnknownApplicationTypeException e) { String msg = "The type of application requested to be un-installed is not supported"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index 53da08ff526..5d06388c131 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import java.util.ArrayList; @@ -207,4 +208,42 @@ public class RequestValidationUtil { } } + public static void validateApplicationInstallationContext(ApplicationWrapper installationCtx) { + int count = 0; + + if (installationCtx.getDeviceIdentifiers() != null && installationCtx.getDeviceIdentifiers().size() > 0) { + count++; + } + if (installationCtx.getUserNameList() != null && installationCtx.getUserNameList().size() > 0) { + count++; + } + if (installationCtx.getRoleNameList() != null && installationCtx.getRoleNameList().size() > 0) { + count++; + } + if (count > 1) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("The incoming request has " + + "more than one application installation criteria defined").build()); + } + } + + public static void validateApplicationUninstallationContext(ApplicationWrapper installationCtx) { + int count = 0; + + if (installationCtx.getDeviceIdentifiers() != null && installationCtx.getDeviceIdentifiers().size() > 0) { + count++; + } + if (installationCtx.getUserNameList() != null && installationCtx.getUserNameList().size() > 0) { + count++; + } + if (installationCtx.getRoleNameList() != null && installationCtx.getRoleNameList().size() > 0) { + count++; + } + if (count > 1) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("The incoming request has " + + "more than one application un-installation criteria defined").build()); + } + } + } From e2c03adec478612116e8c7ba76fed23bf14d1e22 Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 31 May 2016 11:14:37 +0530 Subject: [PATCH 14/18] FIx for https://wso2.org/jira/browse/IOTS-169 --- .../device/mgt/jaxrs/api/impl/GroupImpl.java | 19 ++++++++--- ...n.java => GroupAlreadyExistException.java} | 12 +++---- .../GroupManagementProviderService.java | 4 +-- .../GroupManagementProviderServiceImpl.java | 6 ++-- .../devicemgt/app/conf/config.json | 5 +++ .../pages/cdmf.page.group.create/create.hbs | 24 +++----------- .../pages/cdmf.page.group.create/create.js | 32 +++++++++++++++++++ .../public/js/group-add.js | 16 ++++++++++ .../app/pages/cdmf.page.groups/groups.hbs | 3 +- .../cdmf.page.groups/public/js/listing.js | 3 ++ 10 files changed, 86 insertions(+), 38 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/{GroupAlreadyEixistException.java => GroupAlreadyExistException.java} (78%) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java index 14c63238186..2f0b1d111d6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java @@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; @@ -58,7 +58,11 @@ public class GroupImpl implements Group { public Response createGroup(DeviceGroup group) { String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); if (group == null) { - return Response.status(Response.Status.BAD_REQUEST).build(); + return Response.status(Response.Status.BAD_REQUEST).entity("Group cannot be null").build(); + } else if (group.getName() == null || !group.getName().matches("^[\\S]{3,30}$")) { + String msg = "Provided group name is invalid. Should be in minimum 3 characters long " + + "and should not include any whitespaces."; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } group.setOwner(owner); group.setDateOfCreation(new Date().getTime()); @@ -78,7 +82,7 @@ public class GroupImpl implements Group { groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS, DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS); return Response.status(Response.Status.CREATED).build(); - } catch (GroupAlreadyEixistException e) { + } catch (GroupAlreadyExistException e) { return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build(); } catch (GroupManagementException e) { log.error(e.getErrorMessage(), e); @@ -92,9 +96,14 @@ public class GroupImpl implements Group { @Consumes("application/json") @Produces("application/json") public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, - DeviceGroup deviceGroup) { + DeviceGroup group) { + if (group.getName() == null || !group.getName().matches("^[\\S]{3,30}$")) { + String msg = "Provided group name is invalid. Should be in minimum 3 characters long " + + "and should not include any whitespaces."; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } try { - DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner); + DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(group, groupName, owner); return Response.status(Response.Status.OK).build(); } catch (GroupManagementException e) { log.error(e.getErrorMessage(), e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupAlreadyEixistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupAlreadyExistException.java similarity index 78% rename from components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupAlreadyEixistException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupAlreadyExistException.java index 0ee0960b20a..f849d0952b7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupAlreadyEixistException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupAlreadyExistException.java @@ -21,31 +21,31 @@ package org.wso2.carbon.device.mgt.common.group.mgt; /** * This class represents a custom exception specified for group management */ -public class GroupAlreadyEixistException extends Exception { +public class GroupAlreadyExistException extends Exception { private static final long serialVersionUID = -312678379574816874L; private String errorMessage; - public GroupAlreadyEixistException(String msg, Exception nestedEx) { + public GroupAlreadyExistException(String msg, Exception nestedEx) { super(msg, nestedEx); setErrorMessage(msg); } - public GroupAlreadyEixistException(String message, Throwable cause) { + public GroupAlreadyExistException(String message, Throwable cause) { super(message, cause); setErrorMessage(message); } - public GroupAlreadyEixistException(String msg) { + public GroupAlreadyExistException(String msg) { super(msg); setErrorMessage(msg); } - public GroupAlreadyEixistException() { + public GroupAlreadyExistException() { super(); } - public GroupAlreadyEixistException(Throwable cause) { + public GroupAlreadyExistException(Throwable cause) { super(cause); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 82564aec36f..1b16cc05073 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -22,7 +22,7 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException; @@ -43,7 +43,7 @@ public interface GroupManagementProviderService { * @throws GroupManagementException */ void createGroup(DeviceGroup deviceGroup, String defaultRole, - String[] defaultPermissions) throws GroupManagementException, GroupAlreadyEixistException; + String[] defaultPermissions) throws GroupManagementException, GroupAlreadyExistException; /** * Update existing device group. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 6cecc185e00..dc01ddf5d60 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -29,7 +29,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; @@ -69,7 +69,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid */ @Override public void createGroup(DeviceGroup deviceGroup, String defaultRole, String[] defaultPermissions) - throws GroupManagementException, GroupAlreadyEixistException { + throws GroupManagementException, GroupAlreadyExistException { if (deviceGroup == null) { throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); } @@ -83,7 +83,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid groupId = this.groupDAO.addGroup(groupBroker, tenantId); GroupManagementDAOFactory.commitTransaction(); } else { - throw new GroupAlreadyEixistException("Group exist with name " + deviceGroup.getName()); + throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); } } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json index bef0d5884f6..8d8f82d08b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json @@ -37,6 +37,11 @@ "emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", "emailRegExViolationErrorMsg" : "Provided email is invalid." }, + "groupValidationConfig": { + "groupNameJSRegEx": "^[\\S]{3,30}$", + "groupNameRegExViolationErrorMsg": "Provided group name is invalid.", + "groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces." + }, "roleValidationConfig" : { "rolenameJSRegEx" : "^[\\S]{3,30}$", "rolenameRegExViolationErrorMsg" : "Provided role name is invalid.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs index cc7aeaeb402..bcf105493bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.hbs @@ -1,20 +1,3 @@ -{{! - Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - - WSO2 Inc. 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. -}} {{unit "cdmf.unit.ui.title" pageTitle="Group Management"}} {{#zone "breadcrumbs"}} @@ -49,11 +32,12 @@
- + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js new file mode 100644 index 00000000000..5c646f33f9e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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. + */ + +/** + * Returns the dynamic state to be populated by add-group page. + * + * @param context Object that gets updated with the dynamic state of this page to be presented + * @returns {*} A context object that returns the dynamic state of this page to be presented + */ +function onRequest(context) { + var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); + var page = {}; + page["groupNameJSRegEx"] = devicemgtProps.groupValidationConfig.groupNameJSRegEx; + page["groupNameRegExViolationErrorMsg"] = devicemgtProps.groupValidationConfig.groupNameRegExViolationErrorMsg; + page["groupNameHelpMsg"] = devicemgtProps.groupValidationConfig.groupNameHelpMsg; + return page; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/public/js/group-add.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/public/js/group-add.js index 9e0bc2de9a7..ae6870abd34 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/public/js/group-add.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/public/js/group-add.js @@ -16,6 +16,18 @@ * under the License. */ +/** + * Checks if provided input is valid against RegEx input. + * + * @param regExp Regular expression + * @param inputString Input string to check + * @returns {boolean} Returns true if input matches RegEx + */ +function inputIsValid(regExp, inputString) { + regExp = new RegExp(regExp); + return regExp.test(inputString); +} + $(function () { $("button#add-group-btn").click(function () { @@ -26,6 +38,10 @@ $(function () { $('.wr-validation-summary strong').text("Group Name is a required field. It cannot be empty."); $('.wr-validation-summary').removeClass("hidden"); return false; + } else if (!inputIsValid($("input#name").data("regex"), name)) { + $('.wr-validation-summary strong').text($("input#name").data("errormsg")); + $('.wr-validation-summary').removeClass("hidden"); + return false; } else { var group = {"name": name, "description": description}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.hbs index cb93094c769..263f47d4119 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.hbs @@ -226,8 +226,7 @@
-

Exception at backend. Try Later.

- +

Bad Request. Please contact your administrator.

    Ok     diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/public/js/listing.js index bd447757590..1c16e3dfd18 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/public/js/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/public/js/listing.js @@ -484,6 +484,9 @@ function displayErrors(jqXHR) { showPopup(); if (jqXHR.status == 400) { $(modalPopupContent).html($('#group-400-content').html()); + if (jqXHR.responseText) { + $('#error-msg').html(jqXHR.responseText.replace(new RegExp("\"", 'g'), "")); + } $("a#group-400-link").click(function () { hidePopup(); }); From 3defcfe20d993b4118a251abf94314ba00da318b Mon Sep 17 00:00:00 2001 From: geethkokila Date: Tue, 31 May 2016 11:25:11 +0530 Subject: [PATCH 15/18] Fixing the applicationMgtAdminService for returing activity --- .../ApplicationManagementAdminService.java | 9 ++++++-- ...ApplicationManagementAdminServiceImpl.java | 21 ++++++++++--------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java index c7e2c1a26aa..23b6cba5abd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -48,11 +49,13 @@ public interface ApplicationManagementAdminService { httpMethod = "POST", value = "Application installation API.(Internal API)", notes = "This is an internal API used for application installation on a device.", + response = Activity.class, tags = "Application Management Administrative Service") @ApiResponses(value = { @ApiResponse( code = 202, - message = "OK. \n Install application operation will be delivered to the given devices"), + message = "OK. \n Install application operation will be delivered to the given devices", + response = Activity.class), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -84,11 +87,13 @@ public interface ApplicationManagementAdminService { httpMethod = "POST", value = "Application un-installation API.(Internal API)", notes = "This is an internal API used for application un-installation on a device.", + response = Activity.class, tags = "Application Management Administrative Service") @ApiResponses(value = { @ApiResponse( code = 202, - message = "OK. \n Uninstall application operation will be delivered to the provided devices"), + message = "OK. \n Uninstall application operation will be delivered to the provided devices", + response = Activity.class), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java index e669c73dcbc..bfa8f3a8754 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java @@ -24,6 +24,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.Platform; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.exception.UnknownApplicationTypeException; @@ -57,6 +58,7 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem public Response installApplication(ApplicationWrapper applicationWrapper) { ApplicationManager appManagerConnector; Operation operation = null; + Activity activity = null; RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper); try { @@ -72,20 +74,19 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem } } if (applicationWrapper.getRoleNameList() != null && applicationWrapper.getRoleNameList().size() > 0) { - appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList()); + activity = appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList()); } else if (applicationWrapper.getUserNameList() != null && applicationWrapper.getUserNameList().size() > 0) { - appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList()); + activity = appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList()); } else if (applicationWrapper.getDeviceIdentifiers() != null && applicationWrapper.getDeviceIdentifiers().size() > 0) { - appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } else { throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( "No application installation criteria i.e. user/role/device is given").build()); } } - return Response.status(Response.Status.ACCEPTED).entity("Application installation request has been sent " + - "to the device(s)").build(); + return Response.status(Response.Status.ACCEPTED).entity(activity).build(); } catch (ApplicationManagementException e) { String msg = "ErrorResponse occurred while processing application installation request"; log.error(msg, e); @@ -105,6 +106,7 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem public Response uninstallApplication(ApplicationWrapper applicationWrapper) { ApplicationManager appManagerConnector; org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; + Activity activity = null; RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper); try { @@ -120,20 +122,19 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem } } if (applicationWrapper.getRoleNameList() != null && applicationWrapper.getRoleNameList().size() > 0) { - appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList()); + activity = appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList()); } else if (applicationWrapper.getUserNameList() != null && applicationWrapper.getUserNameList().size() > 0) { - appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList()); + activity = appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList()); } else if (applicationWrapper.getDeviceIdentifiers() != null && applicationWrapper.getDeviceIdentifiers().size() > 0) { - appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } else { throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( "No application un-installation criteria i.e. user/role/device is given").build()); } } - return Response.status(Response.Status.ACCEPTED).entity("Application un-installation request has " + - "been sent to the given device(s)").build(); + return Response.status(Response.Status.ACCEPTED).entity(activity).build(); } catch (ApplicationManagementException e) { String msg = "ErrorResponse occurred while processing application un-installation request"; log.error(msg, e); From 92a732cd411a5930c13926681ff190d55af5193b Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 31 May 2016 11:30:36 +0530 Subject: [PATCH 16/18] Moved redundant texts to constants --- .../carbon/device/mgt/jaxrs/api/impl/GroupImpl.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java index 2f0b1d111d6..97c086bf141 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java @@ -50,6 +50,9 @@ import java.util.List; @SuppressWarnings("NonJaxWsWebServices") public class GroupImpl implements Group { + private static final String GROUP_CANNOT_NULL_MSG = "Group cannot be null."; + private static final String GROUP_NAME_INVALID_MSG = "Provided group name is invalid. Should be in minimum 3 " + + "characters long and should not include any whitespaces."; private static Log log = LogFactory.getLog(GroupImpl.class); @Override @@ -58,11 +61,9 @@ public class GroupImpl implements Group { public Response createGroup(DeviceGroup group) { String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); if (group == null) { - return Response.status(Response.Status.BAD_REQUEST).entity("Group cannot be null").build(); + return Response.status(Response.Status.BAD_REQUEST).entity(GROUP_CANNOT_NULL_MSG).build(); } else if (group.getName() == null || !group.getName().matches("^[\\S]{3,30}$")) { - String msg = "Provided group name is invalid. Should be in minimum 3 characters long " + - "and should not include any whitespaces."; - return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(GROUP_NAME_INVALID_MSG).build(); } group.setOwner(owner); group.setDateOfCreation(new Date().getTime()); @@ -98,9 +99,7 @@ public class GroupImpl implements Group { public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, DeviceGroup group) { if (group.getName() == null || !group.getName().matches("^[\\S]{3,30}$")) { - String msg = "Provided group name is invalid. Should be in minimum 3 characters long " + - "and should not include any whitespaces."; - return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(GROUP_NAME_INVALID_MSG).build(); } try { DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(group, groupName, owner); From fc3d6cccbfc940b970debdcca8577a6126f16f3d Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 12:49:51 +0530 Subject: [PATCH 17/18] Fixing Issues in notification management APIs --- .../device/mgt/jaxrs/NotificationContext.java | 58 ++++ .../device/mgt/jaxrs/NotificationList.java | 106 ++++++ .../device/mgt/jaxrs/beans/ActivityList.java | 58 +--- .../mgt/jaxrs/beans/BasePaginatedResult.java | 72 ++++ .../device/mgt/jaxrs/beans/DeviceList.java | 56 +--- .../mgt/jaxrs/beans/NotificationList.java | 53 +-- .../service/api/DeviceManagementService.java | 1 + .../api/NotificationManagementService.java | 117 +------ .../NotificationManagementServiceImpl.java | 43 +-- ...ApplicationManagementAdminServiceImpl.java | 3 +- .../impl/util/RequestValidationUtil.java | 1 - .../common/EntityDoesNotExistException.java | 45 +++ .../common/notification/mgt/Notification.java | 30 +- .../mgt/NotificationManagementService.java | 43 ++- .../NotificationManagementServiceImpl.java | 260 +++++++-------- .../mgt/dao/impl/NotificationDAOImpl.java | 307 +++++++++--------- 16 files changed, 622 insertions(+), 631 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationContext.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationList.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EntityDoesNotExistException.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationContext.java new file mode 100644 index 00000000000..3d7d48c2f3a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationContext.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; + +@ApiModel(value = "NotificationContext") +public class NotificationContext { + + private DeviceIdentifier deviceId; + private Notification notification; + + public NotificationContext(DeviceIdentifier deviceId, Notification notification) { + this.deviceId = deviceId; + this.notification = notification; + } + + @ApiModelProperty(value = "deviceId") + @JsonProperty("deviceId") + public DeviceIdentifier getDeviceId() { + return deviceId; + } + + public void setDeviceId(DeviceIdentifier deviceId) { + this.deviceId = deviceId; + } + + @ApiModelProperty(value = "notification") + @JsonProperty("notification") + public Notification getNotification() { + return notification; + } + + public void setNotification(Notification notification) { + this.notification = notification; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationList.java new file mode 100644 index 00000000000..641bd5c93ab --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/NotificationList.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; + +import java.util.ArrayList; +import java.util.List; + +@ApiModel(value = "Notifications") +public class NotificationList { + + private int count; + private String next; + private String previous; + + private List notifications = new ArrayList<>(); + + /** + * Number of notifications returned. + */ + @ApiModelProperty(value = "Number of Devices returned.") + @JsonProperty("count") + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + + /** + * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. + */ + @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + + "Empty if no more resources are to be returned.") + @JsonProperty("next") + public String getNext() { + return next; + } + + public void setNext(String next) { + this.next = next; + } + + /** + * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. + */ + @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + + "Empty if current subset is the first subset returned.") + @JsonProperty("previous") + public String getPrevious() { + return previous; + } + + public void setPrevious(String previous) { + this.previous = previous; + } + + /** + **/ + @ApiModelProperty(value = "List of devices returned") + @JsonProperty("devices") + public List getList() { + return notifications; + } + + public void setList(List notifications) { + this.notifications = notifications; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(count).append(",\n"); + sb.append(" next: ").append(next).append(",\n"); + sb.append(" previous: ").append(previous).append(",\n"); + sb.append(" notifications: [").append(notifications).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java index 18eb30c080d..16e9f772a68 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ActivityList.java @@ -28,58 +28,10 @@ import java.util.List; @ApiModel(value = "List of activities", description = "This contains a set of activities that matches a given " + "criteria as a collection") -public class ActivityList { +public class ActivityList extends BasePaginatedResult { - private int count; - private String next; - private String previous; + private List activities; - private List activities = new ArrayList<>(); - - /** - * Number of Devices returned. - */ - @ApiModelProperty(value = "Number of activities returned.") - @JsonProperty("count") - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } - - - /** - * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. - */ - @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + - "Empty if no more resources are to be returned.") - @JsonProperty("next") - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - /** - * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. - */ - @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + - "Empty if current subset is the first subset returned.") - @JsonProperty("previous") - public String getPrevious() { - return previous; - } - - public void setPrevious(String previous) { - this.previous = previous; - } - - /** - **/ @ApiModelProperty(value = "List of devices returned") @JsonProperty("activities") public List getList() { @@ -95,9 +47,9 @@ public class ActivityList { StringBuilder sb = new StringBuilder(); sb.append("{\n"); - sb.append(" count: ").append(count).append(",\n"); - sb.append(" next: ").append(next).append(",\n"); - sb.append(" previous: ").append(previous).append(",\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); sb.append(" devices: [").append(activities).append("\n"); sb.append("]}\n"); return sb.toString(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java new file mode 100644 index 00000000000..9ae3ade67e1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +public class BasePaginatedResult { + + private int count; + private String next; + private String previous; + + /** + * Number of Devices returned. + */ + @ApiModelProperty(value = "Number of resources returned.") + @JsonProperty("count") + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + + /** + * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. + */ + @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + + "Empty if no more resources are to be returned.") + @JsonProperty("next") + public String getNext() { + return next; + } + + public void setNext(String next) { + this.next = next; + } + + /** + * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. + */ + @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + + "Empty if current subset is the first subset returned.") + @JsonProperty("previous") + public String getPrevious() { + return previous; + } + + public void setPrevious(String previous) { + this.previous = previous; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java index a14de34deda..11e7505efc7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java @@ -25,58 +25,10 @@ import org.wso2.carbon.device.mgt.common.Device; import java.util.ArrayList; import java.util.List; -public class DeviceList { - - private int count; - private String next; - private String previous; +public class DeviceList extends BasePaginatedResult { private List devices = new ArrayList<>(); - /** - * Number of Devices returned. - */ - @ApiModelProperty(value = "Number of Devices returned.") - @JsonProperty("count") - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } - - - /** - * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. - */ - @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + - "Empty if no more resources are to be returned.") - @JsonProperty("next") - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - /** - * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. - */ - @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + - "Empty if current subset is the first subset returned.") - @JsonProperty("previous") - public String getPrevious() { - return previous; - } - - public void setPrevious(String previous) { - this.previous = previous; - } - - /** - **/ @ApiModelProperty(value = "List of devices returned") @JsonProperty("devices") public List getList() { @@ -92,9 +44,9 @@ public class DeviceList { StringBuilder sb = new StringBuilder(); sb.append("{\n"); - sb.append(" count: ").append(count).append(",\n"); - sb.append(" next: ").append(next).append(",\n"); - sb.append(" previous: ").append(previous).append(",\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); sb.append(" devices: [").append(devices).append("\n"); sb.append("]}\n"); return sb.toString(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/NotificationList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/NotificationList.java index 9309555af9a..ad2297af857 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/NotificationList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/NotificationList.java @@ -26,55 +26,10 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import java.util.List; @ApiModel(value = "notificationList") -public class NotificationList { +public class NotificationList extends BasePaginatedResult { - private int count; - private String next; - private String previous; private List notifications; - /** - * Number of notifications returned. - */ - @ApiModelProperty(value = "Number of notifications returned.") - @JsonProperty("count") - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } - - - /** - * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. - */ - @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + - "Empty if no more resources are to be returned.") - @JsonProperty("next") - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - /** - * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. - */ - @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + - "Empty if current subset is the first subset returned.") - @JsonProperty("previous") - public String getPrevious() { - return previous; - } - - public void setPrevious(String previous) { - this.previous = previous; - } - @JsonProperty("notifications") @ApiModelProperty("notifications") public List getNotifications() { @@ -90,9 +45,9 @@ public class NotificationList { StringBuilder sb = new StringBuilder(); sb.append("{"); - sb.append(" count: ").append(count).append(","); - sb.append(" next: ").append(next).append(","); - sb.append(" previous: ").append(previous).append(","); + sb.append(" count: ").append(getCount()).append(","); + sb.append(" next: ").append(getNext()).append(","); + sb.append(" previous: ").append(getPrevious()).append(","); sb.append(" notifications: [").append(notifications).append(""); sb.append("]}"); return sb.toString(); 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 46708a16e73..2fad649ab45 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 @@ -805,4 +805,5 @@ public interface DeviceManagementService { required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java index 8cc6f7a916c..bdd73071963 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java @@ -22,6 +22,9 @@ import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.jaxrs.NotificationContext; +import org.wso2.carbon.device.mgt.jaxrs.NotificationList; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -45,16 +48,13 @@ public interface NotificationManagementService { value = "Getting all device notification details.", notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using " + "this REST API", - response = Notification.class, - responseContainer = "List", tags = "Device Notification Management") @ApiResponses( value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the list of notifications.", - response = Notification.class, - responseContainer = "List", + response = NotificationList.class, responseHeaders = { @ResponseHeader( name = "Content-Type", @@ -76,7 +76,8 @@ public interface NotificationManagementService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the notification list.") + message = "Internal Server ErrorResponse. \n Server error occurred while fetching the notification list.", + response = ErrorResponse.class) }) @Permission(scope = "device-notification-view", permissions = { "/permission/admin/device-mgt/admin/notifications/view", @@ -86,7 +87,7 @@ public interface NotificationManagementService { @ApiParam(name = "status", value = "Status of the notification.", allowableValues = "NEW, CHECKED", - required = true) + required = false) @QueryParam("status") String status, @ApiParam( name = "If-Modified-Since", @@ -105,108 +106,4 @@ public interface NotificationManagementService { @QueryParam("limit") int limit); - @PUT - @Path("/{id}/status") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - produces = MediaType.APPLICATION_JSON, - httpMethod = "PUT", - value = "Update the device notification status", - notes = "When a user has read the the device notifications, the device notification status must " - + "change from NEW to CHECKED. Update the device notification status using this REST API.", - tags = "Device Notification Management") - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Notification status has been updated successfully", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the updated device."), - @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 = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 404, - message = "Not Found. \n Resource to be deleted does not exist."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), - @ApiResponse( - code = 500, - message = "Internal Server ErrorResponse. \n " + - "Server error occurred while modifying status of the notification.") - }) - @Permission(scope = "device-notification-modify", - permissions = {"/permission/admin/device-mgt/admin/notifications/modify"}) - Response updateNotificationStatus( - @ApiParam( - name = "id", - value = "Notification identifier.", - required = true) - @PathParam("id") int id, - @ApiParam( - name = "status", - value = "Status of the notification.", - allowableValues = "NEW, CHECKED", - required = true) String status); - - @POST - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - produces = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add a device notification.", - notes = "Add a device notification, which will then be sent to a device.", - tags = "Device Notification Management") - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Notification has been added successfully.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added notification."), - @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 = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), - @ApiResponse( - code = 500, - message = "Internal Server ErrorResponse. \n " + - "Server error occurred while adding the notification.") - }) - @Permission(scope = "device-notification-modify", - permissions = {"/permission/admin/device-mgt/admin/notifications/modify"}) - Response addNotification( - @ApiParam( - name = "notification", - value = "Notification details to be added.", - required = true) Notification notification); - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index 6ec55c73bb1..077996f0b7b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -22,8 +22,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.jaxrs.NotificationContext; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -56,48 +59,16 @@ public class NotificationManagementServiceImpl implements NotificationManagement notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications(); } - if (notifications == null || notifications.size() == 0) { + if (notifications == null) { return Response.status(Response.Status.NOT_FOUND).entity("No notification is available to be " + "retrieved").build(); } return Response.status(Response.Status.OK).entity(notifications).build(); } catch (NotificationManagementException e) { - msg = "ErrorResponse occurred while retrieving notification info"; + msg = "Error occurred while retrieving notification info"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - - @PUT - @Path("/{id}/status") - @Override - public Response updateNotificationStatus(@PathParam("id") int id, String status) { - try { - RequestValidationUtil.validateNotificationId(id); - RequestValidationUtil.validateNotificationStatus(status); - - DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, - Notification.Status.valueOf(status)); - return Response.status(Response.Status.OK).entity("Notification status has successfully been updated").build(); - } catch (NotificationManagementException e) { - String msg = "ErrorResponse occurred while updating notification status"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - - @POST - @Override - public Response addNotification(Notification notification) { - try { - RequestValidationUtil.validateNotification(notification); - - DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification); - return Response.status(Response.Status.OK).entity("Notification has successfully been added").build(); - } catch (NotificationManagementException e) { - String msg = "ErrorResponse occurred while updating notification status."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).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/ApplicationManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java index e669c73dcbc..01caf579f18 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java @@ -128,7 +128,8 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem applicationWrapper.getDeviceIdentifiers().size() > 0) { appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } else { - throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( "No application un-installation criteria i.e. user/role/device is given").build()); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index 5d06388c131..2d437f411c6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -18,7 +18,6 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EntityDoesNotExistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EntityDoesNotExistException.java new file mode 100644 index 00000000000..13b68210014 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EntityDoesNotExistException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.common; + +public class EntityDoesNotExistException extends RuntimeException { + + private static final long serialVersionUID = -3161279331929070297L; + + public EntityDoesNotExistException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public EntityDoesNotExistException(String message, Throwable cause) { + super(message, cause); + } + + public EntityDoesNotExistException(String msg) { + super(msg); + } + + public EntityDoesNotExistException() { + super(); + } + + public EntityDoesNotExistException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java index 2b92a3b9b5f..c5c2656fc62 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java @@ -38,14 +38,9 @@ public class Notification { ALERT } - @JsonProperty(value = "notificationId", required = false) - @ApiModelProperty(name = "notificationId", value = "Defines the notification ID.", required = false) - private int notificationId; - - @JsonProperty(value = "deviceIdentifier", required = true) - @ApiModelProperty(name = "deviceIdentifier", value = "Defines the device identification properties.", - required = true) - private DeviceIdentifier deviceIdentifier; + @JsonProperty(value = "id", required = false) + @ApiModelProperty(name = "id", value = "Defines the notification ID.", required = false) + private int id; @JsonProperty(value = "description", required = false) @ApiModelProperty(name = "description", value = "Provides the message you want to send to the user.", @@ -72,19 +67,11 @@ public class Notification { } public int getNotificationId() { - return notificationId; - } - - public void setNotificationId(int notificationId) { - this.notificationId = notificationId; + return id; } - public DeviceIdentifier getDeviceIdentifier() { - return deviceIdentifier; - } - - public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) { - this.deviceIdentifier = deviceIdentifier; + public void setNotificationId(int id) { + this.id = id; } public String getDescription() { @@ -106,12 +93,11 @@ public class Notification { @Override public String toString() { return "notification {" + - "notificationId='" + notificationId + '\'' + - ", deviceId=" + deviceIdentifier.getId() + - ", deviceType=" + deviceIdentifier.getType() + + " id='" + id + '\'' + ", status=" + status + ", description='" + description + '\'' + ", operationId='" + operationId + '\'' + '}'; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java index 7cd60536d78..303775b73fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java @@ -18,6 +18,8 @@ package org.wso2.carbon.device.mgt.common.notification.mgt; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + import java.util.List; /** @@ -25,50 +27,55 @@ import java.util.List; */ public interface NotificationManagementService { - /** - * Method to add a notification to the database. + /** + * Method to add a notification to the database. * - * @param notification - Notification to be added to database. - * @return boolean status of the operation. - * @throws NotificationManagementException if something goes wrong while adding the Notification. - */ - boolean addNotification(Notification notification) throws NotificationManagementException; + * @param notification - Notification to be added to database. + * @return boolean status of the operation. + * @throws NotificationManagementException + * if something goes wrong while adding the Notification. + */ + boolean addNotification(DeviceIdentifier deviceId, + Notification notification) throws NotificationManagementException; /** * Method to update a notification in the database. * * @param notification - Notification to be updated in the database. * @return boolean status of the operation. - * @throws NotificationManagementException if something goes wrong while updating the Notification. + * @throws NotificationManagementException + * if something goes wrong while updating the Notification. */ - boolean updateNotification(Notification notification) throws NotificationManagementException; + boolean updateNotification(Notification notification) throws NotificationManagementException; /** * Method to update the notification status of a Notification in the database. * * @param notificationId - Notification id of the notification to be updated. - * @param status - New notification status. + * @param status - New notification status. * @return boolean status of the operation. - * @throws NotificationManagementException if something goes wrong while updating the Notification. + * @throws NotificationManagementException + * if something goes wrong while updating the Notification. */ - boolean updateNotificationStatus(int notificationId, Notification.Status status) throws - NotificationManagementException; + boolean updateNotificationStatus(int notificationId, Notification.Status status) throws + NotificationManagementException; /** * Method to fetch all the notifications in the database. * * @return List of all Notifications in the database. * @throws NotificationManagementException + * */ - List getAllNotifications() throws NotificationManagementException; + List getAllNotifications() throws NotificationManagementException; /** - * * @param status - Status of the notifications to be fetched from database. * @return A list of notifications matching the given status. - * @throws NotificationManagementException if something goes wrong while fetching the Notification. + * @throws NotificationManagementException + * if something goes wrong while fetching the Notification. */ - List getNotificationsByStatus(Notification.Status status) throws - NotificationManagementException; + List getNotificationsByStatus(Notification.Status status) throws + NotificationManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index 3681a026f6f..858643e8874 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -21,6 +21,8 @@ package org.wso2.carbon.device.mgt.core.notification.mgt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.EntityDoesNotExistException; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; @@ -40,133 +42,133 @@ import java.util.List; */ public class NotificationManagementServiceImpl implements NotificationManagementService { - private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class); - - private NotificationDAO notificationDAO; - private DeviceDAO deviceDAO; - - public NotificationManagementServiceImpl() { - this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO(); - this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); - } - - @Override - public boolean addNotification(Notification notification) throws NotificationManagementException { - boolean status = false; - int deviceId, tenantId; - if (log.isDebugEnabled()) { - log.debug("Adding a Notification : [" + notification.toString() + "]"); - } - try { - tenantId = NotificationDAOUtil.getTenantId(); - DeviceManagementDAOFactory.openConnection(); - Device device = deviceDAO.getDevice(notification.getDeviceIdentifier(), tenantId); - deviceId = device.getId(); - } catch (SQLException e) { - throw new NotificationManagementException("Error occurred while opening a connection to" + - " the data source", e); - } catch (DeviceManagementDAOException e) { - throw new NotificationManagementException("Error occurred while retriving device data for " + - " adding notification", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - try { - NotificationManagementDAOFactory.beginTransaction(); - int notificationId = notificationDAO.addNotification(deviceId, tenantId, notification); - NotificationManagementDAOFactory.commitTransaction(); - - if (log.isDebugEnabled()) { - log.debug("Notification id : " + notificationId +" was added to the table."); - } - if(notificationId > 0) { - status = true; - } - } catch (TransactionManagementException e) { - NotificationManagementDAOFactory.rollbackTransaction(); - throw new NotificationManagementException("Error occurred while adding notification", e); - } finally { - NotificationManagementDAOFactory.closeConnection(); - } - return status; - } - - @Override - public boolean updateNotification(Notification notification) throws NotificationManagementException { - boolean status = false; - if (log.isDebugEnabled()) { - log.debug("Updating Notification : [" + notification.toString() + "]"); - } - try { - NotificationManagementDAOFactory.beginTransaction(); - if(notificationDAO.updateNotification(notification) > 0 ) { - status = true; - } - NotificationManagementDAOFactory.commitTransaction(); - - if (log.isDebugEnabled()) { - log.debug("Notification id : " + notification.getNotificationId() + - " has updated successfully."); - } - } catch (TransactionManagementException e) { - NotificationManagementDAOFactory.rollbackTransaction(); - throw new NotificationManagementException("Error occurred while updating notification ", e); - } finally { - NotificationManagementDAOFactory.closeConnection(); - } - return status; - } - - @Override - public boolean updateNotificationStatus(int notificationId, Notification.Status status) - throws NotificationManagementException { - boolean operationStatus = false; - if (log.isDebugEnabled()) { - log.debug("Updating Notification id : " + notificationId); - } - try { - NotificationManagementDAOFactory.beginTransaction(); - if(notificationDAO.updateNotificationStatus(notificationId, status) > 0 ) { - operationStatus = true; - } - NotificationManagementDAOFactory.commitTransaction(); - - if (log.isDebugEnabled()) { - log.debug("Notification id : " + notificationId +" has updated successfully."); - } - } catch (TransactionManagementException e) { - NotificationManagementDAOFactory.rollbackTransaction(); - throw new NotificationManagementException("Error occurred while updating notification", e); - } finally { - NotificationManagementDAOFactory.closeConnection(); - } - return operationStatus; - } - - @Override - public List getAllNotifications() throws NotificationManagementException{ - try { - NotificationManagementDAOFactory.openConnection(); - return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId()); - } catch (SQLException e) { - throw new NotificationManagementException("Error occurred while opening a connection to" + - " the data source", e); - } finally { - NotificationManagementDAOFactory.closeConnection(); - } - } - - @Override - public List getNotificationsByStatus(Notification.Status status) - throws NotificationManagementException{ - try { - NotificationManagementDAOFactory.openConnection(); - return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId()); - } catch (SQLException e) { - throw new NotificationManagementException("Error occurred while opening a connection " + - "to the data source", e); - } finally { - NotificationManagementDAOFactory.closeConnection(); - } - } + private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class); + + private NotificationDAO notificationDAO; + private DeviceDAO deviceDAO; + + public NotificationManagementServiceImpl() { + this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO(); + this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); + } + + @Override + public boolean addNotification(DeviceIdentifier deviceId, + Notification notification) throws NotificationManagementException { + if (log.isDebugEnabled()) { + log.debug("Adding a Notification : [" + notification.toString() + "]"); + } + int notificationId; + int tenantId = NotificationDAOUtil.getTenantId(); + + Device device = this.getDevice(deviceId, tenantId); + if (device == null) { + throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() + + "' and id '" + deviceId.getId() + "'"); + } + + try { + NotificationManagementDAOFactory.beginTransaction(); + notificationId = notificationDAO.addNotification(device.getId(), tenantId, notification); + NotificationManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while adding notification", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + if (log.isDebugEnabled()) { + log.debug("Notification id : " + notificationId + " was added to the table."); + } + return true; + } + + private Device getDevice(DeviceIdentifier deviceId, int tenantId) throws NotificationManagementException { + Device device; + try { + DeviceManagementDAOFactory.openConnection(); + device = deviceDAO.getDevice(deviceId, tenantId); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection to" + + " the data source", e); + } catch (DeviceManagementDAOException e) { + throw new NotificationManagementException("Error occurred while retriving device data for " + + " adding notification", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return device; + } + + @Override + public boolean updateNotification(Notification notification) throws NotificationManagementException { + if (log.isDebugEnabled()) { + log.debug("Updating Notification : [" + notification.toString() + "]"); + } + try { + NotificationManagementDAOFactory.beginTransaction(); + notificationDAO.updateNotification(notification); + NotificationManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while updating notification ", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + if (log.isDebugEnabled()) { + log.debug("Notification id : " + notification.getNotificationId() + + " has updated successfully."); + } + return true; + } + + @Override + public boolean updateNotificationStatus(int notificationId, Notification.Status status) + throws NotificationManagementException { + if (log.isDebugEnabled()) { + log.debug("Updating Notification id : " + notificationId); + } + try { + NotificationManagementDAOFactory.beginTransaction(); + notificationDAO.updateNotificationStatus(notificationId, status); + NotificationManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while updating notification", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + if (log.isDebugEnabled()) { + log.debug("Notification id : " + notificationId + " has updated successfully."); + } + return true; + } + + @Override + public List getAllNotifications() throws NotificationManagementException { + try { + NotificationManagementDAOFactory.openConnection(); + return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId()); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection to" + + " the data source", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getNotificationsByStatus(Notification.Status status) + throws NotificationManagementException { + try { + NotificationManagementDAOFactory.openConnection(); + return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId()); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection " + + "to the data source", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java index 1e435e4cbe8..00f9bc39ac6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java @@ -18,9 +18,6 @@ package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; @@ -36,167 +33,157 @@ import java.util.List; */ public class NotificationDAOImpl implements NotificationDAO { - private static final Log log = LogFactory.getLog(NotificationDAOImpl.class); + @Override + public int addNotification(int deviceId, int tenantId, + Notification notification) throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs; + int notificationId = -1; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?)"; + stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + stmt.setInt(1, deviceId); + stmt.setInt(2, notification.getOperationId()); + stmt.setString(3, notification.getStatus().toString()); + stmt.setString(4, notification.getDescription()); + stmt.setInt(5, tenantId); + stmt.execute(); + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + notificationId = rs.getInt(1); + } + } catch (Exception e) { + throw new NotificationManagementException("Error occurred while adding the " + + "Notification for device id : " + deviceId, + e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, null); + } + return notificationId; + } - @Override - public int addNotification(int deviceId, int tenantId, Notification notification) throws - NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs; - int notificationId = -1; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = - "INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) " + - "VALUES (?, ?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - stmt.setInt(1, deviceId); - stmt.setInt(2, notification.getOperationId()); - stmt.setString(3, notification.getStatus().toString()); - stmt.setString(4, notification.getDescription()); - stmt.setInt(5, tenantId); - stmt.execute(); - rs = stmt.getGeneratedKeys(); - if (rs.next()) { - notificationId = rs.getInt(1); - } - } catch (Exception e) { - throw new NotificationManagementException("Error occurred while adding the " + - "Notification for device id : " + deviceId, - e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, null); - } - return notificationId; - } + @Override + public int updateNotification(Notification notification) + throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + int rows; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " + + "WHERE NOTIFICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, notification.getOperationId()); + stmt.setString(2, notification.getStatus().toString()); + stmt.setString(3, notification.getDescription()); + stmt.setInt(4, notification.getNotificationId()); + rows = stmt.executeUpdate(); + } catch (Exception e) { + throw new NotificationManagementException("Error occurred while updating the " + + "Notification id : " + notification.getNotificationId(), e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, null); + } + return rows; + } - @Override - public int updateNotification(Notification notification) - throws NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - int rows; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " + - "WHERE NOTIFICATION_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, notification.getOperationId()); - stmt.setString(2, notification.getStatus().toString()); - stmt.setString(3, notification.getDescription()); - stmt.setInt(4, notification.getNotificationId()); - rows = stmt.executeUpdate(); - } catch (Exception e) { - throw new NotificationManagementException("Error occurred while updating the " + - "Notification id : " + notification.getNotificationId(), e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, null); - } - return rows; - } + @Override + public int updateNotificationStatus(int notificationId, Notification.Status status) + throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + int rows; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, status.toString()); + stmt.setInt(2, notificationId); + rows = stmt.executeUpdate(); + } catch (Exception e) { + throw new NotificationManagementException("Error occurred while updating the status of " + + "Notification id : " + notificationId, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, null); + } + return rows; + } - @Override - public int updateNotificationStatus(int notificationId, Notification.Status status) - throws NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - int rows; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, status.toString()); - stmt.setInt(2, notificationId); - rows = stmt.executeUpdate(); - } catch (Exception e) { - throw new NotificationManagementException("Error occurred while updating the status of " + - "Notification id : " + notificationId, e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, null); - } - return rows; - } + @Override + public List getAllNotifications(int tenantId) throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(this.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } - @Override - public List getAllNotifications(int tenantId) - throws NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List notifications = null; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = - "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + - " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + - "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + - "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - rs = stmt.executeQuery(); - notifications = new ArrayList<>(); - while (rs.next()) { - notifications.add(this.getNotification(rs)); - } - } catch (SQLException e) { - throw new NotificationManagementException( - "Error occurred while retrieving information of all notifications", e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, rs); - } - return notifications; - } + @Override + public List getNotificationsByStatus(Notification.Status status, + int tenantId) throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(this.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } - @Override - public List getNotificationsByStatus(Notification.Status status, int tenantId) - throws NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List notifications = null; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + - " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + - "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + - "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + - "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + - "AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); - stmt.setInt(3, tenantId); - rs = stmt.executeQuery(); - notifications = new ArrayList<>(); - while (rs.next()) { - notifications.add(this.getNotification(rs)); - } - } catch (SQLException e) { - throw new NotificationManagementException( - "Error occurred while retrieving information of all " + - "notifications by status : " + status, e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, rs); - } - return notifications; - } + private Notification getNotification(ResultSet rs) throws SQLException { + Notification notification = new Notification(); + notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); + notification.setOperationId(rs.getInt("OPERATION_ID")); + notification.setDescription(rs.getString("DESCRIPTION")); + notification.setStatus(rs.getString("STATUS")); + return notification; + } - private Notification getNotification(ResultSet rs) throws SQLException { - Notification notification = new Notification(); - notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); - notification.setDeviceIdentifier(this.getDeviceIdentifier(rs)); - notification.setOperationId(rs.getInt("OPERATION_ID")); - notification.setDescription(rs.getString("DESCRIPTION")); - notification.setStatus(rs.getString("STATUS")); - return notification; - } - - private DeviceIdentifier getDeviceIdentifier(ResultSet rs) throws SQLException { - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - identifier.setType(rs.getString("DEVICE_TYPE")); - return identifier; - } } \ No newline at end of file From 9f481456143ea937269999c5e06301f4dd593960 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 13:12:57 +0530 Subject: [PATCH 18/18] Improving device admin service impl --- .../admin/DeviceManagementAdminService.java | 3 ++ .../DeviceManagementAdminServiceImpl.java | 23 ++++++++++--- .../util/UnauthorizedAccessException.java | 34 +++++++++++++++++++ 3 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/UnauthorizedAccessException.java 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 2112a89e81a..2ed4403b681 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 @@ -65,6 +65,9 @@ public interface DeviceManagementAdminService { @ApiResponse( code = 304, message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), + @ApiResponse( + code = 401, + message = "Unauthorized.\n The requested resource access is unauthorized"), @ApiResponse( code = 406, message = "Not Acceptable.\n The requested media type is not supported"), 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 9a07245cd25..7c6d7795913 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 @@ -20,9 +20,14 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +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.DeviceManagementException; +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.impl.util.UnauthorizedAccessException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -45,18 +50,28 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { - List devices; try { - devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name); - if (devices == null || devices.size() == 0) { + int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { + throw new UnauthorizedAccessException( + new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage( + "Current logged in user is not authorized to perform this operation").build()); + } + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); + + List devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name); + if (devices == null) { return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" + name + "', is currently enrolled in the system").build(); } return Response.status(Response.Status.OK).entity(devices).build(); } catch (DeviceManagementException e) { - String msg = "ErrorResponse occurred while fetching the devices that carry the name '" + name + "'"; + String msg = "Error occurred while fetching the devices that carry the name '" + name + "'"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/UnauthorizedAccessException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/UnauthorizedAccessException.java new file mode 100644 index 00000000000..c0f05c9c57d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/UnauthorizedAccessException.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.util; + +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class UnauthorizedAccessException extends WebApplicationException { + + private static final long serialVersionUID = 147943579458906890L; + + public UnauthorizedAccessException(ErrorResponse error) { + super(Response.status(Response.Status.UNAUTHORIZED).entity(error).build()); + } + +}