fixing conflicts and improving swagger annotations and validations

revert-70aa11f8
inoshperera 9 years ago
commit ee948abc9d

@ -1,9 +1,18 @@
package org.wso2.carbon.certificate.mgt.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.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/scep")
public interface CertificateMgtService {
/**
@ -13,8 +22,38 @@ public interface CertificateMgtService {
* @return X509Certificate type sign certificate.
*/
@POST
@Path("signcsr")
@Produces({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN})
Response getSignedCertFromCSR(String binarySecurityToken);
@Path("/sign-csr")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiOperation(
consumes = MediaType.TEXT_PLAIN,
produces = MediaType.TEXT_PLAIN,
httpMethod = "POST",
value = "Process a given CSR and return signed certificates.",
notes = "This will return a signed certificate upon a given CSR.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the device location.",
response = String.class),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while retrieving signed certificate.",
response = ErrorResponse.class)
})
@Permission(scope = "sign-csr", permissions = {"/permission/admin/device-mgt/scep/sign-csr"})
Response getSignedCertFromCSR(
@ApiParam(
name = "If-Modified-Since",
value = "Validates if the requested variant has not been modified since the time specified",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince,
String binarySecurityToken);
}

@ -5,6 +5,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator;
import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.jaxrs.exception.UnexpectedServerErrorException;
import org.wso2.carbon.certificate.mgt.jaxrs.api.CertificateMgtService;
import org.wso2.carbon.certificate.mgt.jaxrs.exception.Message;
@ -14,15 +16,16 @@ import javax.ws.rs.core.Response;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
@Path("/scep")
public class CertificateMgtServiceImpl implements CertificateMgtService {
private static Log log = LogFactory.getLog(CertificateMgtServiceImpl.class);
@POST
@Path("signcsr")
@Produces({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN})
public Response getSignedCertFromCSR(String binarySecurityToken) {
@Path("/sign-csr")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
public Response getSignedCertFromCSR(
@HeaderParam("If-Modified-Since") String ifModifiedSince, String binarySecurityToken) {
Message message = new Message();
X509Certificate signedCert;
String singedCertificate;
@ -41,11 +44,13 @@ public class CertificateMgtServiceImpl implements CertificateMgtService {
} catch (KeystoreException e) {
String msg = "Error occurred while fetching certificate.";
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 (CertificateEncodingException e) {
String msg = "Error occurred while encoding the certificate.";
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());
}
}
}

@ -0,0 +1,79 @@
/*
* 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.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
@ApiModel(description = "Error List Item")
public class ErrorListItem {
@NotNull
private String code = null;
@NotNull
private String message = null;
@ApiModelProperty(required = true, value = "")
@JsonProperty("code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ErrorListItem() {
}
public ErrorListItem(String code, String msg) {
this.code = code;
this.message = msg;
}
/**
* Description about individual errors occurred
*/
@ApiModelProperty(required = true, value = "Description about individual errors occurred")
@JsonProperty("message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("errorItem {\n");
sb.append(" code: ").append(code).append("\n");
sb.append(" message: ").append(message).append("\n");
sb.append("}\n");
return sb.toString();
}
}

@ -0,0 +1,193 @@
/*
* 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.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(description = "Error Response")
public class ErrorResponse {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> errorItems = new ArrayList<>();
private ErrorResponse() {
}
@JsonProperty(value = "code")
@ApiModelProperty(required = true, value = "")
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
@JsonProperty(value = "message")
@ApiModelProperty(required = true, value = "ErrorResponse message.")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@JsonProperty(value = "description")
@ApiModelProperty(value = "A detail description about the error message.")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty(value = "moreInfo")
@ApiModelProperty(value = "Preferably an url with more details about the error.")
public String getMoreInfo() {
return moreInfo;
}
public void setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
}
public void addErrorListItem(ErrorListItem item) {
this.errorItems.add(item);
}
/**
* If there are more than one error list them out. \nFor example, list out validation errors by each field.
*/
@JsonProperty(value = "errorItems")
@ApiModelProperty(value = "If there are more than one error list them out. \n" +
"For example, list out validation errors by each field.")
public List<ErrorListItem> getErrorItems() {
return errorItems;
}
public void setErrorItems(List<ErrorListItem> error) {
this.errorItems = error;
}
@Override
public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("{");
// boolean cont = false;
// if (code != null) {
// cont = true;
// sb.append(" \"code\": ").append(code);
// }
// if (message != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"message\": \"").append(message).append("\"");
// }
// if (description != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"description\": ").append(description).append("\"");
// }
// if (moreInfo != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"moreInfo\": \"").append(moreInfo).append("\"");
// }
// if (error != null && error.size() > 0) {
// if (cont) {
// sb.append(",");
// }
// sb.append(" \"errorItems\": ").append(error);
// }
// sb.append("}");
// return sb.toString();
return null;
}
public static class ErrorResponseBuilder {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> error;
public ErrorResponseBuilder() {
this.error = new ArrayList<>();
}
public ErrorResponseBuilder setCode(long code) {
this.code = code;
return this;
}
public ErrorResponseBuilder setMessage(String message) {
this.message = message;
return this;
}
public ErrorResponseBuilder setDescription(String description) {
this.description = description;
return this;
}
public ErrorResponseBuilder setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
return this;
}
public ErrorResponseBuilder addErrorItem(String code, String msg) {
ErrorListItem item = new ErrorListItem();
item.setCode(code);
item.setMessage(msg);
this.error.add(item);
return this;
}
public ErrorResponse build() {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(code);
errorResponse.setMessage(message);
errorResponse.setErrorItems(error);
errorResponse.setDescription(description);
errorResponse.setMoreInfo(moreInfo);
return errorResponse;
}
}
}

@ -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.certificate.mgt.jaxrs.exception;
import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class UnexpectedServerErrorException extends WebApplicationException {
private static final long serialVersionUID = 147943679458906890L;
public UnexpectedServerErrorException(ErrorResponse error) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
}
}

@ -33,7 +33,7 @@
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/emm-admin/certificate/GetSignCSR</path>
<url>/certificates/signcsr</url>
<url>/certificates/scep/signcsr</url>
<method>POST</method>
<scope>emm_admin</scope>
</Permission>

@ -48,13 +48,9 @@
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>admin-certificate</warName>
<warName>api#certificate-mgt#v1.0</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
</plugins>
</build>
@ -79,7 +75,7 @@
<copy todir="${basedir}/../../../repository/deployment/server/webapps"
overwrite="true">
<fileset dir="${basedir}/target">
<include name="admin-certificate.war"/>
<include name="api#certificate-mgt#v1.0.war"/>
</fileset>
</copy>
</tasks>

@ -1,123 +0,0 @@
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;
}

@ -0,0 +1,257 @@
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Api(value = "Certificate Management", description = "This API carries all certificate management related operations " +
"such as get all the available devices, etc.")
@Path("/admin/certificates")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface CertificateManagementAdminService {
/**
* 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,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a SSL certificate",
notes = "Add a new SSL certificate",
tags = "Certificate Management")
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "Created. \n Certificates have successfully been added",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the added certificates."),
@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 = 303,
message = "See Other. \n Source can be retrieved from the URL specified at the Location header.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@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 Error. \n Server error occurred while adding certificates.",
response = ErrorResponse.class)
})
@Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"})
Response addCertificate(
@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,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of an SSL CertificateManagementAdminService",
notes = "Get the client side SSL certificate details",
tags = "Certificate Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched information of the device.",
response = CertificateResponse.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No device is found under the provided type and id."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving information requested certificate.",
response = ErrorResponse.class)
})
@Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"})
Response getCertificate(
@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,
@ApiParam(
name = "If-Modified-Since",
value = "Validates if the requested variant has not been modified since the time specified",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince
);
/**
* Get all certificates in a paginated manner.
*
* @return paginated result of certificate.
*/
@GET
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get certificates",
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",
tags = "Certificate Management"
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n List of certificates enrolled in the system",
response = CertificateList.class,
responseContainer = "List",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 303,
message = "See Other. \n " +
"Source can be retrieved from the URL specified at the Location header.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving all certificates enrolled in the system.",
response = ErrorResponse.class)
})
@Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"})
Response getAllCertificates(
@ApiParam(
name = "offset",
value = "Starting point within the complete list of items qualified.",
required = false)
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Maximum size of resource array to return.",
required = false)
@QueryParam("limit") int limit,
@ApiParam(
name = "If-Modified-Since",
value = "Validates if the requested variant has not been modified since the time specified",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince);
@DELETE
@Path("/{serialNumber}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Delete an SSL certificate",
notes = "Delete an SSL certificate that's on the client end",
tags = "Certificate Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Certificate has successfully been removed"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while removing the certificate.",
response = ErrorResponse.class)})
@Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"})
Response removeCertificate(
@ApiParam(
name = "serialNumber",
value = "Provide the serial number of the "
+ "certificate that you wish to delete",
required = true)
@PathParam("serialNumber") String serialNumber);
}

@ -0,0 +1,35 @@
/*
* 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;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.Serializable;
public class InputValidationException extends WebApplicationException implements Serializable {
private static final long serialVersionUID = 147843589458906890L;
public InputValidationException(ErrorResponse error) {
super(Response.status(Response.Status.BAD_REQUEST).entity(error).build());
}
}

@ -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.certificate.mgt.cert.jaxrs.api;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class UnexpectedServerErrorException extends WebApplicationException {
private static final long serialVersionUID = 147943679458906890L;
public UnexpectedServerErrorException(ErrorResponse error) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
}
}

@ -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.certificate.mgt.cert.jaxrs.api.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;
}
}

@ -0,0 +1,55 @@
/*
* 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.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import java.util.ArrayList;
import java.util.List;
public class CertificateList extends BasePaginatedResult {
private List<CertificateResponse> certificates = new ArrayList<>();
@ApiModelProperty(value = "List of certificates returned")
@JsonProperty("certificates")
public List<CertificateResponse> getList() {
return certificates;
}
public void setList(List<CertificateResponse> certificates) {
this.certificates = certificates;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.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(" certificates: [").append(certificates).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -0,0 +1,79 @@
/*
* 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.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
@ApiModel(description = "Error List Item")
public class ErrorListItem {
@NotNull
private String code = null;
@NotNull
private String message = null;
@ApiModelProperty(required = true, value = "")
@JsonProperty("code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ErrorListItem() {
}
public ErrorListItem(String code, String msg) {
this.code = code;
this.message = msg;
}
/**
* Description about individual errors occurred
*/
@ApiModelProperty(required = true, value = "Description about individual errors occurred")
@JsonProperty("message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("errorItem {\n");
sb.append(" code: ").append(code).append("\n");
sb.append(" message: ").append(message).append("\n");
sb.append("}\n");
return sb.toString();
}
}

@ -0,0 +1,193 @@
/*
* 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.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(description = "Error Response")
public class ErrorResponse {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> errorItems = new ArrayList<>();
private ErrorResponse() {
}
@JsonProperty(value = "code")
@ApiModelProperty(required = true, value = "")
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
@JsonProperty(value = "message")
@ApiModelProperty(required = true, value = "ErrorResponse message.")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@JsonProperty(value = "description")
@ApiModelProperty(value = "A detail description about the error message.")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty(value = "moreInfo")
@ApiModelProperty(value = "Preferably an url with more details about the error.")
public String getMoreInfo() {
return moreInfo;
}
public void setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
}
public void addErrorListItem(ErrorListItem item) {
this.errorItems.add(item);
}
/**
* If there are more than one error list them out. \nFor example, list out validation errors by each field.
*/
@JsonProperty(value = "errorItems")
@ApiModelProperty(value = "If there are more than one error list them out. \n" +
"For example, list out validation errors by each field.")
public List<ErrorListItem> getErrorItems() {
return errorItems;
}
public void setErrorItems(List<ErrorListItem> error) {
this.errorItems = error;
}
@Override
public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("{");
// boolean cont = false;
// if (code != null) {
// cont = true;
// sb.append(" \"code\": ").append(code);
// }
// if (message != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"message\": \"").append(message).append("\"");
// }
// if (description != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"description\": ").append(description).append("\"");
// }
// if (moreInfo != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"moreInfo\": \"").append(moreInfo).append("\"");
// }
// if (error != null && error.size() > 0) {
// if (cont) {
// sb.append(",");
// }
// sb.append(" \"errorItems\": ").append(error);
// }
// sb.append("}");
// return sb.toString();
return null;
}
public static class ErrorResponseBuilder {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> error;
public ErrorResponseBuilder() {
this.error = new ArrayList<>();
}
public ErrorResponseBuilder setCode(long code) {
this.code = code;
return this;
}
public ErrorResponseBuilder setMessage(String message) {
this.message = message;
return this;
}
public ErrorResponseBuilder setDescription(String description) {
this.description = description;
return this;
}
public ErrorResponseBuilder setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
return this;
}
public ErrorResponseBuilder addErrorItem(String code, String msg) {
ErrorListItem item = new ErrorListItem();
item.setCode(code);
item.setMessage(msg);
this.error.add(item);
return this;
}
public ErrorResponse build() {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(code);
errorResponse.setMessage(message);
errorResponse.setErrorItems(error);
errorResponse.setDescription(description);
errorResponse.setMoreInfo(moreInfo);
return errorResponse;
}
}
}

@ -1,181 +0,0 @@
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<org.wso2.carbon.certificate.mgt.core.bean.Certificate> 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> 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<CertificateResponse> 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();
}
}
}

@ -0,0 +1,138 @@
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.CertificateManagementAdminService;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.UnexpectedServerErrorException;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil;
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.Response;
import java.util.ArrayList;
import java.util.List;
@Path("/admin/certificates")
public class CertificateManagementAdminServiceImpl implements CertificateManagementAdminService {
private static Log log = LogFactory.getLog(CertificateManagementAdminServiceImpl.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 addCertificate(EnrollmentCertificate[] enrollmentCertificates) {
CertificateManagementService certificateService;
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> 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.").build();
} catch (KeystoreException e) {
String msg = "Error occurred while converting PEM file to X509Certificate.";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).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(
@PathParam("serialNumber") String serialNumber,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
RequestValidationUtil.validateSerialNumber(serialNumber);
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
List<CertificateResponse> certificateResponse;
try {
certificateResponse = certificateService.searchCertificates(serialNumber);
return Response.status(Response.Status.OK).entity(certificateResponse).build();
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
/**
* Get all certificates in a paginated manner.
*
* @param offset index of the first record to be fetched
* @param limit number of records to be fetched starting from the start index.
* @return paginated result of certificate.
*/
@GET
public Response getAllCertificates(
@QueryParam("offset") int offset,
@QueryParam("limit") int limit,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
RequestValidationUtil.validatePaginationInfo(offset, limit);
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
PaginationRequest paginationRequest = new PaginationRequest(offset, limit);
try {
PaginationResult result = certificateService.getAllCertificates(paginationRequest);
CertificateList certificates = new CertificateList();
certificates.setCount(result.getRecordsTotal());
certificates.setList((List<CertificateResponse>) result.getData());
return Response.status(Response.Status.OK).entity(certificates).build();
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while fetching all certificates.";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
@DELETE
@Path("/{serialNumber}")
public Response removeCertificate(@PathParam("serialNumber") String serialNumber) {
RequestValidationUtil.validateSerialNumber(serialNumber);
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
try {
boolean status = certificateService.removeCertificate(serialNumber);
if (!status) {
Response.status(Response.Status.NOT_FOUND).entity("No certificate is found with the given " +
"serial number '" + serialNumber + "'");
}
return Response.status(Response.Status.OK).entity("Certificate that carries the serial number '" +
serialNumber + "' has been removed").build();
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
}

@ -0,0 +1,44 @@
/*
* 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.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
public void destroy() {
//do nothing
}
public void init(FilterConfig filterConfig) throws ServletException {
//do nothing
}
}

@ -41,7 +41,7 @@ public class DeviceMgtAPIUtils {
ctx.getOSGiService(CertificateManagementService.class, null);
if (certificateManagementService == null) {
String msg = "CertificateImpl Management service not initialized.";
String msg = "CertificateManagementAdminServiceImpl Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}

@ -0,0 +1,48 @@
/*
* 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.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.InputValidationException;
public class RequestValidationUtil {
public static void validateSerialNumber(String serialNumber) {
if (serialNumber == null || serialNumber.isEmpty()) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Serial number cannot be null or empty").build());
}
}
public static void validatePaginationInfo(int offset, int limit) {
if (offset < 0) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Offset number cannot be negative").build());
}
if (limit < 0) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Limit number cannot be negative").build());
}
}
}

@ -29,39 +29,31 @@
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/emm-admin/certificate/GetSignCSR</path>
<url>/certificates/signcsr</url>
<method>POST</method>
<scope>emm_admin</scope>
</Permission>
<!-- Certificate related APIs -->
<!-- CertificateManagementAdminService related APIs -->
<Permission>
<name>Save certificate in the database</name>
<path>/device-mgt/admin/certificate/save</path>
<url>/certificates</url>
<name>Save certificate</name>
<path>/device-mgt/admin/certificate/Save</path>
<url>/admin/certificates</url>
<method>POST</method>
</Permission>
<Permission>
<name>get certificate in the database</name>
<name>Get certificate</name>
<path>/device-mgt/admin/certificate/Get</path>
<url>/certificates/*</url>
<url>/admin/certificates/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>get certificate in the database</name>
<name>Get all certificates</name>
<path>/device-mgt/admin/certificate/GetAll</path>
<url>/certificates</url>
<url>/admin/certificates</url>
<method>GET</method>
</Permission>
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/admin/certificate/Get</path>
<url>/certificates/*</url>
<name>Remove certificate</name>
<path>/device-mgt/admin/certificate/Remove</path>
<url>/admin/certificates/*</url>
<method>DELETE</method>
</Permission>
<!-- End of Certificate related APIs -->
<!-- End of CertificateManagementAdminService related APIs -->
</PermissionConfiguration>

@ -26,6 +26,7 @@
<jaxrs:server id="services" address="/">
<jaxrs:serviceBeans>
<ref bean="certificateServiceBean"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
@ -34,15 +35,6 @@
<ref bean="swaggerWriter"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="certificateService" address="/certificates">
<jaxrs:serviceBeans>
<ref bean="certificateServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers"/>
<bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource"/>
@ -51,15 +43,16 @@
<property name="resourcePackage" value="org.wso2.carbon.certificate.mgt.cert.jaxrs.api"/>
<property name="version" value="1.0.0"/>
<property name="host" value="localhost:9443"/>
<property name="basePath" value="/"/>
<property name="title" value="Device Management Admin Service API Definitions"/>
<property name="schemes" value="https" />
<property name="basePath" value="/api/certificate-mgt/v1.0"/>
<property name="title" value="Certificate Management Admin Service API Definitions"/>
<property name="contact" value="dev@wso2.org"/>
<property name="license" value="Apache 2.0"/>
<property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<property name="scan" value="true"/>
</bean>
<bean id="certificateServiceBean" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl.CertificateImpl"/>
<bean id="certificateServiceBean" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl.CertificateManagementAdminServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.GsonMessageBodyHandler"/>
<bean id="errorHandler" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.ErrorHandler"/>

@ -25,6 +25,11 @@
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<init-param>
<param-name>swagger.security.filter</param-name>
<param-value>ApiAuthorizationFilterImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
@ -63,4 +68,14 @@
</user-data-constraint>
</security-constraint>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

@ -252,10 +252,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
stmt.setString(1, serialNumber);
stmt.setInt(2, tenantId);
if(stmt.executeUpdate() > 0) {
return true;
}
return false;
return stmt.executeUpdate() > 0;
} catch (SQLException e) {
String errorMsg =
"Unable to get the read the certificate with serial" + serialNumber;

@ -173,7 +173,7 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe
try {
CertificateManagementDAOFactory.beginTransaction();
CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO();
Boolean status = certificateDAO.removeCertificate(serialNumber);
boolean status = certificateDAO.removeCertificate(serialNumber);
CertificateManagementDAOFactory.commitTransaction();
return status;
} catch (TransactionManagementException e) {

@ -21,34 +21,14 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "UserCredentialWrapper", description = "User credentials are included in this class.")
public class UserCredentialWrapper {
@ApiModel(value = "OldPasswordResetWrapper", description = "User credentials are included in this class.")
public class OldPasswordResetWrapper extends PasswordResetWrapper{
@ApiModelProperty(name = "username", value = "Username of the user.", required = true )
private String username;
/*
Base64 encoded password
*/
@ApiModelProperty(name = "oldPassword", value = "Old password of the user.", required = true )
private String oldPassword;
@ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true )
private String newPassword;
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getOldPassword() {
return oldPassword;

@ -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.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "PasswordResetWrapper", description = "User credential is included in this class.")
public class PasswordResetWrapper {
/*
Base64 encoded password
*/
@ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true )
private String newPassword;
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}

@ -0,0 +1,55 @@
/*
* 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.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.policy.mgt.common.Policy;
import java.util.List;
@ApiModel(value = "Policy List")
public class PolicyList extends BasePaginatedResult {
private List<Policy> policies;
@ApiModelProperty(value = "List of policies returned")
@JsonProperty("policies")
public List<Policy> getList() {
return policies;
}
public void setList(List<Policy> policies) {
this.policies = policies;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.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(" roles: [").append(policies).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -21,21 +21,20 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
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 java.util.List;
@ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy "
+ "Wrappers")
public class PolicyWrapper {
@ApiModelProperty(name = "id", value = "The policy ID", required = true)
private int id;
@ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the"
+ " policy", required = true)
private Profile profile;
@ApiModelProperty(name = "policyName", value = "The name of the policy", required = true)
private String policyName;
@ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true)
private String description;
@ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the"
+ " following non-compliance rules:\n"
+ "Enforce - Forcefully enforce the policies on the devices\n"
@ -44,8 +43,7 @@ public class PolicyWrapper {
+ "violation unknown to the user and the administrator can take the necessary actions with regard"
+ " to the reported", required = true)
private String compliance;
@ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true)
private List<String> roles;
@ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the "
+ "following values:\n"
+ "ANY - The policy will be applied on the BYOD and COPE device types\n"
@ -53,26 +51,21 @@ public class PolicyWrapper {
+ "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE "
+ "device type", required = true)
private String ownershipType;
@ApiModelProperty(name = "devices", value = "Lists out the devices the policy is enforced on",
@ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the"
+ " policy", required = true)
private Profile profile;
@ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true)
private List<String> roles;
@ApiModelProperty(name = "deviceIdentifiers", value = "Lists out the devices the policy is enforced on",
required = true)
private List<Device> devices;
private List<DeviceIdentifier> deviceIdentifiers;
@ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced",
required = true)
private List<String> users;
@ApiModelProperty(name = "tenantId", value = "The ID of the tenant that created the policy",
required = true)
private int tenantId;
@ApiModelProperty(name = "profileId", value = "The ID of each profile that is in the selected policy",
required = true)
private int profileId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Profile getProfile() {
return profile;
@ -122,12 +115,12 @@ public class PolicyWrapper {
this.ownershipType = ownershipType;
}
public List<Device> getDevices() {
return devices;
public List<DeviceIdentifier> getDeviceIdentifiers() {
return deviceIdentifiers;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
public void setDeviceIdentifier(List<DeviceIdentifier> deviceIdentifier) {
this.deviceIdentifiers = deviceIdentifiers;
}
public List<String> getUsers() {
@ -138,20 +131,4 @@ public class PolicyWrapper {
this.users = users;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public int getProfileId() {
return profileId;
}
public void setProfileId(int profileId) {
this.profileId = profileId;
}
}

@ -0,0 +1,55 @@
/*
* 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.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
@ApiModel(value = "Role List")
public class RoleList extends BasePaginatedResult {
private List<String> roles;
@ApiModelProperty(value = "List of roles returned")
@JsonProperty("roles")
public List<String> getList() {
return roles;
}
public void setList(List<String> roles) {
this.roles = roles;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.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(" roles: [").append(roles).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -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.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(value = "List of users", description = "This contains a set of users that matches a given " +
"criteria as a collection")
public class UserList extends BasePaginatedResult {
private List<UserWrapper> users = new ArrayList<>();
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("users")
public List<UserWrapper> getList() {
return users;
}
public void setList(List<UserWrapper> users) {
this.users = users;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.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(" users: [").append(users).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -76,9 +76,13 @@ public interface ActivityInfoProviderService {
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 401,
message = ". \n Invalid request or validation error."),
@ApiResponse(
code = 404,
message = "Not Found. \n No activity is found under the provided id."),
message = "Not Found. \n No activity is found under the provided id.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ -131,6 +135,10 @@ public interface ActivityInfoProviderService {
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n No activities found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),

@ -78,13 +78,24 @@ public interface DeviceManagementService {
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."),
@ApiResponse(
code = 400,
message = "The incoming request has more than one selection criteria defined through query" +
" parameters.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "No device is currently enrolled with the server.",
response = ErrorResponse.class),
@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 fetching the device list.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
@Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDevices(
@ -170,10 +181,12 @@ 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 No device is found under the provided type and id."),
message = "Not Found. \n No device is found under the provided type and id.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ -201,69 +214,74 @@ public interface DeviceManagementService {
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince);
// @POST
// @ApiOperation(
// consumes = MediaType.APPLICATION_JSON,
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "POST",
// value = "Retrieve devices information from the supplied device identifies.",
// notes = "This will return device information such as CPU usage, memory usage etc for supplied device " +
// "identifiers.",
// response = DeviceInfo.class,
// responseContainer = "List",
// tags = "Device Management")
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 200,
// message = "OK. \n Information of the submitted list of devices is returned",
// response = DeviceInfo.class,
// responseContainer = "List",
// responseHeaders = {
// @ResponseHeader(
// name = "Content-Type",
// description = "The content type of the body"),
// @ResponseHeader(
// name = "ETag",
// description = "Entity Tag of the response resource.\n" +
// "Used by caches, or in conditional requests."),
// @ResponseHeader(
// name = "Last-Modified",
// description = "Date and time the resource has been modified the last time.\n" +
// "Used by caches, or in conditional requests.")}),
// @ApiResponse(
// code = 303,
// message = "See Other. \n Source can be retrieved from the URL specified at the Location header.",
// responseHeaders = {
// @ResponseHeader(
// name = "Content-Location",
// description = "The Source URL of the document.")}),
// @ApiResponse(
// code = 304,
// message = "Not Modified. \n " +
// "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."),
// @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.")
// })
// @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
// Response getDevicesInfo(
// @ApiParam(
// name = "deviceIds",
// value = "List of device identifiers",
// required = true) List<DeviceIdentifier> deviceIds,
// @ApiParam(
// name = "If-Modified-Since",
// value = "Timestamp of the last modified date",
// required = false)
// @HeaderParam("If-Modified-Since") String timestamp);
@POST
@Path("/get-info")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Retrieve devices information from the supplied device identifies.",
notes = "This will return device information such as CPU usage, memory usage etc for supplied device " +
"identifiers.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Information of the submitted list of devices is returned",
response = DeviceInfo.class,
responseContainer = "List",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 303,
message = "See Other. \n Source can be retrieved from the URL specified at the Location header.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No device information is available for the device list submitted.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. 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 getDevicesInfo(
@ApiParam(
name = "If-Modified-Since",
value = "Timestamp of the last modified date",
required = false)
@HeaderParam("If-Modified-Since") String timestamp,
@ApiParam(
name = "deviceIds",
value = "List of device identifiers",
required = true) List<DeviceIdentifier> deviceIds);
@GET
@ -295,11 +313,16 @@ public interface DeviceManagementService {
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
message = "Not Modified. Empty body because the client already has the latest " +
"version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No device is found under the provided type and id."),
message = "Not Found. \n No device is found under the provided type and id.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
@ -346,9 +369,14 @@ public interface DeviceManagementService {
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No device is found under the provided type and id."),
message = "Not Found. \n No device is found under the provided type and id.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "ErrorResponse occurred while getting the device location.",
@ -394,9 +422,14 @@ public interface DeviceManagementService {
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Location details are not available for the given devices."),
message = "Location details are not available for the given devices.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "ErrorResponse occurred while getting the device location.",
@ -462,7 +495,8 @@ public interface DeviceManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Device of which the feature list is requested, is not found."),
message = "Not Found. \n Device of which the feature list is requested, is not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ -528,6 +562,11 @@ public interface DeviceManagementService {
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Acceptable.\n TIt is likely that no device is found upon the " +
"provided filters",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ -603,7 +642,8 @@ public interface DeviceManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Device of which the application list is requested, is not found."),
message = "Not Found. \n Device of which the application list is requested, is not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ -611,7 +651,7 @@ public interface DeviceManagementService {
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while retrieving installed application list of the device.",
response = ErrorResponse.class)
response = ErrorResponse.class)
})
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
@ -691,7 +731,8 @@ public interface DeviceManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Device of which the operation list is requested, is not found."),
message = "Not Found. \n Device of which the operation list is requested, is not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ -778,7 +819,8 @@ public interface DeviceManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Device of which the effective policy is requested, is not found."),
message = "Not Found. \n Device of which the effective policy is requested, is not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),

@ -71,6 +71,15 @@ public interface NotificationManagementService {
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid notification status type " +
"received. Valid status types are NEW | CHECKED",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No notification is available to be retrieved.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.policy.mgt.common.Policy;
@ -66,7 +67,8 @@ public interface PolicyManagementService {
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
"Used by caches, or in conditional requests.")
}),
@ApiResponse(
code = 303,
message = "See Other. \n Source can be retrieved from the URL specified at the Location header.",
@ -76,14 +78,21 @@ public interface PolicyManagementService {
description = "The Source URL of the document.")}),
@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 = 401,
message = "Not Found. \n Current logged in user is not authorized to add policies.",
response = ErrorResponse.class),
@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 a new policy.")})
"Server error occurred while adding a new policy.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response addPolicy(
@ApiParam(
@ -123,12 +132,18 @@ public interface PolicyManagementService {
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 400,
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"),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching policies.")
message = ("Internal Server ErrorResponse. \n Server error occurred while fetching " +
"policies."),
response = ErrorResponse.class)
})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getPolicies(
@ -181,13 +196,17 @@ public interface PolicyManagementService {
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n No policy is found with the given id."),
message = "Not Found. \n No policy is found with the given id.",
response = ErrorResponse.class
),
@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 fetching the policy.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the " +
"policy.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getPolicy(
@ -234,17 +253,20 @@ public interface PolicyManagementService {
"Used by caches, or in conditional requests.")}),
@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 deleted does not exist."),
message = "Not Found. \n Resource to be deleted does not exist.",
response = ErrorResponse.class),
@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 updating the policy.")
"Server error occurred while updating the policy.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"})
Response updatePolicy(
@ -258,6 +280,7 @@ public interface PolicyManagementService {
required = true) PolicyWrapper policy);
@POST
@Path("/remove-policy")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
@ -272,17 +295,20 @@ public interface PolicyManagementService {
message = "OK. \n Policies have successfully been removed"),
@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 deleted does not exist."),
message = "Not Found. \n Resource to be deleted does not exist.",
response = ErrorResponse.class),
@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 bulk removing policies.")
"Server error occurred while bulk removing policies.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/remove"})
Response removePolicies(
@ -303,8 +329,21 @@ public interface PolicyManagementService {
tags = "Device Policy Management")
@ApiResponses(
value = {
@ApiResponse(code = 200, message = "Policies have been successfully activated."),
@ApiResponse(code = 500, message = "ErrorResponse in activating policies.")
@ApiResponse(
code = 200,
message = "Policies have been successfully activated."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "ErrorResponse in activating policies.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {
"/permission/admin/device-mgt/admin/policies/update",
@ -324,8 +363,21 @@ public interface PolicyManagementService {
"is in the active state to the inactive state.",
tags = "Device Policy Management")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Policies have been successfully deactivated."),
@ApiResponse(code = 500, message = "ErrorResponse in deactivating policies.")
@ApiResponse(
code = 200,
message = "Policies have been successfully deactivated."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "ErrorResponse in deactivating policies.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {
"/permission/admin/device-mgt/admin/policies/update",

@ -22,6 +22,8 @@ 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 org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@ -43,18 +45,15 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the list of roles.",
responseContainer = "List",
notes = "If you wish to get the details of all the roles in EMM, you can do so using this REST API. All " +
"internal roles, roles created for Service-providers and application related roles are omitted.",
response = String.class,
tags = "Role Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested list of roles.",
response = String.class,
responseContainer = "List",
response = RoleList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
@ -71,12 +70,17 @@ public interface RoleManagementService {
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@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 fetching requested list of roles.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {
"/permission/admin/device-mgt/admin/roles/list",
@ -147,15 +151,21 @@ public interface RoleManagementService {
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@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 fetching the permission list of the requested role.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getPermissionsOfRole(
@ -200,16 +210,24 @@ public interface RoleManagementService {
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
message = "Not Modified. \n Empty body because the client has already the latest version of" +
" the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@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 fetching the requested role.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the " +
"requested role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getRole(
@ -260,14 +278,16 @@ public interface RoleManagementService {
description = "The Source URL of the document.")}),
@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 = 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 a new role.")
"Server error occurred while adding a new role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"})
Response addRole(
@ -307,7 +327,8 @@ public interface RoleManagementService {
"Used by caches, or in conditional requests.")}),
@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 deleted does not exist."),
@ -317,7 +338,8 @@ public interface RoleManagementService {
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the role.")
"Server error occurred while updating the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateRole(
@ -343,13 +365,18 @@ public interface RoleManagementService {
@ApiResponse(
code = 200,
message = "OK. \n Role has successfully been removed"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while removing the role.")
"Server error occurred while removing the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"})
Response deleteRole(
@ -395,7 +422,8 @@ public interface RoleManagementService {
"Used by caches, or in conditional requests.")}),
@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 deleted does not exist."),
@ -405,7 +433,8 @@ public interface RoleManagementService {
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the user list of the role.")
"Server error occurred while updating the user list of the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateUsersOfRole(

@ -21,13 +21,14 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api;
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.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserList;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
@API(name = "User Management API", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"})
@ -76,13 +77,18 @@ public interface UserManagementService {
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 409,
message = "Conflict. \n User already exist.",
response = ErrorResponse.class),
@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 a new user.")
"Server error occurred while adding a new user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"})
Response addUser(
@ -124,13 +130,16 @@ public interface UserManagementService {
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@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 fetching the requested user.")
message = "Internal Server ErrorResponse. \n Server error occurred while" +
" fetching the requested user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"})
Response getUser(
@ -179,14 +188,16 @@ public interface UserManagementService {
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@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 updating the user.")
"Server error occurred while updating the user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/update"})
Response updateUser(
@ -214,11 +225,14 @@ public interface UserManagementService {
message = "OK. \n User has successfully been removed"),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource to be deleted does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while removing the user.")
"Server error occurred while removing the user.",
response = ErrorResponse.class
)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/remove"})
Response removeUser(
@ -260,13 +274,16 @@ public interface UserManagementService {
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource to be deleted does not exist.",
response = ErrorResponse.class),
@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 fetching the role list assigned to the user.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the role list" +
" assigned to the user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"})
Response getRolesOfUser(
@ -280,14 +297,14 @@ public interface UserManagementService {
value = "Get user list",
notes = "If you wish to get the details of all the users registered with EMM, you can do so "
+ "using the REST API",
response = UserWrapper.class,
response = UserList.class,
responseContainer = "List",
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested role.",
response = UserWrapper.class,
response = UserList.class,
responseContainer = "List",
responseHeaders = {
@ResponseHeader(
@ -304,20 +321,21 @@ public interface UserManagementService {
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."),
@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 fetching the user list.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the user list.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getUsers(
@ApiParam(
name = "filter",
value = "Username of the user details to be fetched.",
required = true)
required = false)
@QueryParam("filter") String filter,
@ApiParam(
name = "If-Modified-Since",
@ -336,7 +354,7 @@ public interface UserManagementService {
@QueryParam("limit") int limit);
@GET
@Path("/usernames")
@Path("/search/usernames")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
@ -376,7 +394,9 @@ public interface UserManagementService {
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 username list that matches the given filter.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the username " +
"list that matches the given filter.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getUserNames(
@ -406,7 +426,7 @@ public interface UserManagementService {
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
httpMethod = "PUT",
value = "Changing the user password.",
notes = "A user is able to change the password to secure their EMM profile via this REST API.",
tags = "User Management")
@ -416,7 +436,8 @@ public interface UserManagementService {
message = "OK. \n Credentials of the user have been updated successfully"),
@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 deleted does not exist."),
@ -426,7 +447,8 @@ public interface UserManagementService {
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating credentials of the user.")
"Server error occurred while updating credentials of the user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/login"})
Response resetPassword(
@ -438,6 +460,6 @@ public interface UserManagementService {
@ApiParam(
name = "credentials",
value = "Credential.",
required = true) UserCredentialWrapper credentials);
required = true) OldPasswordResetWrapper credentials);
}

@ -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.common.Device;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@ -64,16 +65,23 @@ public interface DeviceManagementAdminService {
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
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"),
message = "Unauthorized.\n The requested resource access is unauthorized",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found.\n No device found that matches the given name.",
response = ErrorResponse.class),
@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 fetching the device list.")
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
Response getDevicesByName(
@ApiParam(

@ -27,73 +27,73 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
@Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " +
"'internal' components to log in as an admin user and do a selected number of operations. " +
"Further, this is strictly restricted to admin users only ")
//@Path("/admin/groups")
//@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_JSON)
//@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " +
// "'internal' components to log in as an admin user and do a selected number of operations. " +
// "Further, this is strictly restricted to admin users only ")
public interface GroupManagementAdminService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get groups by the name.",
notes = "Get devices the name of device and tenant.",
response = DeviceGroupWrapper.class,
responseContainer = "List",
tags = "Group Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.",
response = DeviceGroupWrapper.class,
responseContainer = "List",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@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 fetching the group list.")
})
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getGroupsOfUser(
@ApiParam(
name = "username",
value = "Username of the user.",
required = true)
@QueryParam("username") String username,
@ApiParam(
name = "If-Modified-Since",
value = "Timestamp of the last modified date",
required = false)
@HeaderParam("If-Modified-Since") String timestamp,
@ApiParam(
name = "offset",
value = "Starting point within the complete list of items qualified.",
required = false)
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Maximum size of resource array to return.",
required = false)
@QueryParam("limit") int limit);
// @GET
// @ApiOperation(
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "GET",
// value = "Get groups by the name.",
// notes = "Get devices the name of device and tenant.",
// response = DeviceGroupWrapper.class,
// responseContainer = "List",
// tags = "Group Management Administrative Service")
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.",
// response = DeviceGroupWrapper.class,
// responseContainer = "List",
// responseHeaders = {
// @ResponseHeader(
// name = "Content-Type",
// description = "The content type of the body"),
// @ResponseHeader(
// name = "ETag",
// description = "Entity Tag of the response resource.\n" +
// "Used by caches, or in conditional requests."),
// @ResponseHeader(
// name = "Last-Modified",
// description = "Date and time the resource has been modified the last time.\n" +
// "Used by caches, or in conditional requests."),
// }),
// @ApiResponse(
// code = 304,
// message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
// @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 fetching the group list.")
// })
// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
// Response getGroupsOfUser(
// @ApiParam(
// name = "username",
// value = "Username of the user.",
// required = true)
// @QueryParam("username") String username,
// @ApiParam(
// name = "If-Modified-Since",
// value = "Timestamp of the last modified date",
// required = false)
// @HeaderParam("If-Modified-Since") String timestamp,
// @ApiParam(
// name = "offset",
// value = "Starting point within the complete list of items qualified.",
// required = false)
// @QueryParam("offset") int offset,
// @ApiParam(
// name = "limit",
// value = "Maximum size of resource array to return.",
// required = false)
// @QueryParam("limit") int limit);
//
}

@ -20,7 +20,8 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@ -49,7 +50,8 @@ public interface UserManagementAdminService {
message = "OK. \n Credentials of the user have been updated successfully"),
@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 deleted does not exist."),
@ -59,10 +61,11 @@ public interface UserManagementAdminService {
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating credentials of the user.")
"Server error occurred while updating credentials of the user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/login"})
Response resetPassword(
Response resetUserPassword(
@ApiParam(
name = "username",
value = "Username of the user.",
@ -71,6 +74,6 @@ public interface UserManagementAdminService {
@ApiParam(
name = "credentials",
value = "Credential.",
required = true) UserCredentialWrapper credentials);
required = true) PasswordResetWrapper credentials);
}

@ -75,7 +75,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
List<Activity> activities;
List<Activity> activities = null;
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();

@ -77,14 +77,18 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
PaginationResult result;
if (type != null) {
request.setDeviceType(type);
result = dms.getDevicesByType(request);
} else if (user != null) {
request.setOwner(user);
result = dms.getDevicesOfUser(request);
} else if (ownership != null) {
RequestValidationUtil.validateOwnershipType(ownership);
request.setOwnership(ownership);
result = dms.getDevicesByOwnership(request);
} else if (status != null) {
RequestValidationUtil.validateStatus(status);
request.setStatus(status);
result = dms.getDevicesByStatus(request);
} else {
result = dms.getAllDevices(request);
@ -133,28 +137,30 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(deviceInfo).build();
}
//
// @POST
// @Override
// public Response getDevicesInfo(
// List<DeviceIdentifier> deviceIds,
// @HeaderParam("If-Modified-Since") String timestamp) {
// DeviceInformationManager informationManager;
// List<DeviceInfo> deviceInfo;
// try {
// informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
// deviceInfo = informationManager.getDevicesInfo(deviceIds);
// if (deviceInfo == null) {
// return Response.status(Response.Status.NOT_FOUND).entity("No device information is available for the " +
// "device list submitted").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();
// }
// return Response.status(Response.Status.OK).entity(deviceInfo).build();
// }
@POST
@Path("/get-info")
@Override
public Response getDevicesInfo(
@HeaderParam("If-Modified-Since") String timestamp,
List<DeviceIdentifier> deviceIds) {
DeviceInformationManager informationManager;
List<DeviceInfo> deviceInfo;
try {
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceInfo = informationManager.getDevicesInfo(deviceIds);
if (deviceInfo == null) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No device information " +
"is available for the device list submitted").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();
}
return Response.status(Response.Status.OK).entity(deviceInfo).build();
}
@GET
@Path("/{type}/{id}")
@ -274,11 +280,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("limit") int limit, SearchContext searchContext) {
SearchManagerService searchManagerService;
List<DeviceWrapper> devices;
if(searchContext == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Search context is " +
"empty.").build());
}
try {
searchManagerService = DeviceMgtAPIUtils.getSearchManagerService();
devices = searchManagerService.search(searchContext);
@ -288,10 +289,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
if (devices == null) {
if (devices == null || devices.size() == 0) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("It is likely that no device " +
"is found upon the provided type and id").build());
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("It is likely that no device is found upon " +
"the provided search filters").build());
}
return Response.status(Response.Status.OK).entity(devices).build();
}

@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
@ -31,6 +32,8 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyList;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
import org.wso2.carbon.policy.mgt.common.Policy;
@ -55,52 +58,67 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
public Response addPolicy(PolicyWrapper policyWrapper) {
RequestValidationUtil.validatePolicyDetails(policyWrapper);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
Policy policy = this.getPolicyFromWrapper(policyWrapper);
List<Device> devices = policy.getDevices();
if (devices != null && devices.size() == 1) {
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(devices.get(0).getDeviceIdentifier(),
devices.get(0).getType());
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
try {
if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) {
throw new UnauthorizedAccessException(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage("Current logged in user " +
"is not authorized to add policies").build());
try {
Policy policy = this.getPolicyFromWrapper(policyWrapper);
List<Device> devices = policy.getDevices();
if (devices != null && devices.size() == 1) {
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(devices.get(0).getDeviceIdentifier(),
devices.get(0).getType());
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
try {
if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) {
throw new UnauthorizedAccessException(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage
("Current logged in user is not authorized to add policies").build());
}
} catch (DeviceAccessAuthorizationException e) {
String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
} catch (DeviceAccessAuthorizationException e) {
String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.addPolicy(policy);
return Response.status(Response.Status.OK).entity("Policy has been added successfully").build();
return Response.status(Response.Status.CREATED).entity("Policy has been added successfully").build();
} catch (PolicyManagementException e) {
String msg = "ErrorResponse occurred while adding policy";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while retrieving device list.";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) {
Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) throws DeviceManagementException {
Policy policy = new Policy();
policy.setPolicyName(policyWrapper.getPolicyName());
policy.setProfileId(policyWrapper.getProfileId());
policy.setDescription(policyWrapper.getDescription());
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
policy.setOwnershipType(policyWrapper.getOwnershipType());
policy.setRoles(policyWrapper.getRoles());
policy.setUsers(policyWrapper.getUsers());
policy.setTenantId(policyWrapper.getTenantId());
policy.setCompliance(policyWrapper.getCompliance());
//TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here.
List<Device> devices = null;
List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers();
if (deviceIdentifiers != null) {
for (DeviceIdentifier id : deviceIdentifiers) {
devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id));
}
}
policy.setDevices(devices);
policy.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
return policy;
}
@ -112,6 +130,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
@QueryParam("limit") int limit) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<Policy> policies;
List<Policy> filteredPolicies;
PolicyList targetPolicies = new PolicyList();
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicies();
@ -119,13 +139,20 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No policies found.").build());
}
targetPolicies.setCount(policies.size());
filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit);
if (filteredPolicies.size() == 0) {
return Response.status(Response.Status.NOT_FOUND).entity("No policies found.").build();
}
targetPolicies.setList(filteredPolicies);
} catch (PolicyManagementException e) {
String msg = "ErrorResponse occurred while retrieving all available policies";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity(policies).build();
return Response.status(Response.Status.OK).entity(targetPolicies).build();
}
@GET
@ -156,9 +183,14 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
public Response updatePolicy(@PathParam("id") int id, PolicyWrapper policyWrapper) {
RequestValidationUtil.validatePolicyDetails(policyWrapper);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
Policy policy = this.getPolicyFromWrapper(policyWrapper);
try {
Policy policy = this.getPolicyFromWrapper(policyWrapper);
policy.setId(id);
PolicyAdministratorPoint pap = policyManagementService.getPAP();
Policy exisitingPolicy = pap.getPolicy(id);
if (exisitingPolicy == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Policy not found.").build();
}
pap.updatePolicy(policy);
return Response.status(Response.Status.OK).entity("Policy has successfully been updated.").build();
} catch (PolicyManagementException e) {
@ -166,10 +198,16 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while retrieving the device list.";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
@POST
@Path("/remove-policy")
@Override
public Response removePolicies(List<Integer> policyIds) {
RequestValidationUtil.validatePolicyIds(policyIds);
@ -178,8 +216,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
for (int i : policyIds) {
org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i);
if (!pap.deletePolicy(policy)) {
Policy policy = pap.getPolicy(i);
if (policy == null || !pap.deletePolicy(policy)) {
policyDeleted = false;
}
}
@ -198,16 +236,21 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
}
}
@POST
@PUT
@Path("/activate-policy")
@Override
public Response activatePolicies(List<Integer> policyIds) {
RequestValidationUtil.validatePolicyIds(policyIds);
boolean isPolicyActivated = false;
try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP();
for (int i : policyIds) {
pap.activatePolicy(i);
Policy policy = pap.getPolicy(i);
if (policy != null) {
pap.activatePolicy(i);
isPolicyActivated = true;
}
}
} catch (PolicyManagementException e) {
String msg = "ErrorResponse occurred while activating policies";
@ -215,19 +258,31 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated").build();
if (isPolicyActivated) {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated")
.build();
} else {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Selected policies have " +
"not been activated").build());
}
}
@POST
@PUT
@Path("/deactivate-policy")
@Override
public Response deactivatePolicies(List<Integer> policyIds) {
RequestValidationUtil.validatePolicyIds(policyIds);
boolean isPolicyDeActivated = false;
try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP();
for (int i : policyIds) {
pap.inactivatePolicy(i);
Policy policy = pap.getPolicy(i);
if (policy != null) {
pap.inactivatePolicy(i);
isPolicyDeActivated = true;
}
}
} catch (PolicyManagementException e) {
String msg = "Exception in inactivating policies.";
@ -235,8 +290,14 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity("Selected policies have been successfully " +
"deactivated").build();
if (isPolicyDeActivated) {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully " +
"deactivated").build();
} else {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Selected policies have " +
"not been deactivated").build());
}
}
}

@ -26,11 +26,13 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil;
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.beans.RoleWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
import org.wso2.carbon.user.mgt.UserRealmProxy;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import org.wso2.carbon.user.mgt.common.UserAdminException;
@ -57,19 +59,27 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset, @QueryParam("limit") int limit) {
List<String> filteredRoles;
RoleList targetRoles = new RoleList();
try {
filteredRoles = getRolesFromUserStore();
if (filteredRoles == null || filteredRoles.size() == 0) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No roles found.").build());
}
targetRoles.setCount(filteredRoles.size());
filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(), offset, limit);
if (filteredRoles.size() == 0) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No roles found").build());
}
targetRoles.setList(filteredRoles);
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving roles from the underlying user stores";
String msg = "Error occurred while retrieving roles from the underlying user stores";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity(filteredRoles).build();
return Response.status(Response.Status.OK).entity(targetRoles).build();
}
@GET
@ -95,12 +105,12 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
return Response.status(Response.Status.OK).entity(rolePermissions).build();
} catch (UserAdminException e) {
String msg = "ErrorResponse occurred while retrieving the permissions of role '" + roleName + "'";
String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the underlying user realm attached to the " +
String msg = "Error occurred while retrieving the underlying user realm attached to the " +
"current logged in user";
log.error(msg, e);
throw new UnexpectedServerErrorException(
@ -164,7 +174,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
.build());
}
} catch (UserStoreException | UserAdminException e) {
String msg = "ErrorResponse occurred while retrieving the user role '" + roleName + "'";
String msg = "Error occurred while retrieving the user role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
@ -185,6 +195,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@POST
@Override
public Response addRole(RoleWrapper roleWrapper) {
RequestValidationUtil.validateRoleDetails(roleWrapper);
RequestValidationUtil.validateRoleName(roleWrapper.getRoleName());
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
@ -202,12 +213,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while adding role '" + roleWrapper.getRoleName() + "'";
String msg = "Error occurred while adding role '" + roleWrapper.getRoleName() + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).build();
return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " +
"successfully been added").build();
}
@PUT
@ -215,6 +227,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@Override
public Response updateRole(@PathParam("roleName") String roleName, RoleWrapper roleWrapper) {
RequestValidationUtil.validateRoleName(roleName);
RequestValidationUtil.validateRoleDetails(roleWrapper);
String newRoleName = roleWrapper.getRoleName();
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
@ -246,12 +259,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
}
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while updating role '" + roleName + "'";
String msg = "Error occurred while updating role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).build();
return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " +
"successfully been updated").build();
}
@DELETE
@ -269,15 +283,16 @@ public class RoleManagementServiceImpl implements RoleManagementService {
// Delete all authorizations for the current role before deleting
authorizationManager.clearRoleAuthorization(roleName);
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while deleting the role '" + roleName + "'";
String msg = "Error occurred while deleting the role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).build();
return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " +
"successfully been deleted").build();
}
@POST
@PUT
@Path("/{roleName}/users")
@Override
public Response updateUsersOfRole(@PathParam("roleName") String roleName, List<String> users) {
@ -298,12 +313,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while updating the users of the role '" + roleName + "'";
String msg = "Error occurred while updating the users of the role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).build();
return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " +
"successfully been updated with the user list").build();
}
private List<String> getRolesFromUserStore() throws UserStoreException {

@ -27,11 +27,12 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.ConflictException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserList;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
@ -42,7 +43,6 @@ import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.util.*;
@Path("/users")
@ -81,7 +81,7 @@ public class UserManagementServiceImpl implements UserManagementService {
this.inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() + " was successfully added.");
log.debug("User '" + userWrapper.getUsername() + "' has successfully been added.");
}
// returning response with success state
return Response.status(Response.Status.OK).entity("User by username: " + userWrapper.getUsername() +
@ -149,10 +149,10 @@ public class UserManagementServiceImpl implements UserManagementService {
Properties props = new Properties();
props.setProperty("username", usernameBits[1]);
props.setProperty("domain-name", tenantDomain);
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("first-name", getClaimValue(usernameBits[1], Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("password", password);
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
String recipient = getClaimValue(usernameBits[1], Constants.USER_CLAIM_EMAIL_ADDRESS);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
@ -188,8 +188,9 @@ public class UserManagementServiceImpl implements UserManagementService {
log.debug("User by username: " + username + " does not exist.");
}
// returning response with bad request state
return Response.status(Response.Status.NOT_FOUND).entity(
"User by username: " + username + " does not exist").build();
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User doesn't exist.")
.build());
}
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving information of the user '" + username + "'";
@ -211,9 +212,8 @@ public class UserManagementServiceImpl implements UserManagementService {
userWrapper.getEmailAddress());
if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
// Decoding Base64 encoded password
byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
new String(decodedBytes, "UTF-8"));
userWrapper.getPassword());
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
}
List<String> currentRoles = this.getFilteredRoles(userStoreManager, userWrapper.getUsername());
@ -246,11 +246,12 @@ public class UserManagementServiceImpl implements UserManagementService {
log.debug("User by username: " + userWrapper.getUsername() +
" doesn't exists. Therefore, request made to update user was refused.");
}
return Response.status(Response.Status.CONFLICT).entity("User by username: " +
userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was " +
"refused.").build();
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " +
userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user" +
" was refused.").build());
}
} catch (UserStoreException | UnsupportedEncodingException e) {
} catch (UserStoreException e) {
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
log.error(msg, e);
throw new UnexpectedServerErrorException(
@ -296,8 +297,9 @@ public class UserManagementServiceImpl implements UserManagementService {
log.debug("User by username: " + username + " does not exist for removal.");
}
// returning response with bad request state
return Response.status(Response.Status.NOT_FOUND).entity("User by username: " + username +
" does not exist for removal.").build();
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " +
username + " does not exist for removal.").build());
}
} catch (UserStoreException e) {
String msg = "Exception in trying to remove user by username: " + username;
@ -307,7 +309,7 @@ public class UserManagementServiceImpl implements UserManagementService {
}
}
@POST
@GET
@Path("/{username}/roles")
@Override
public Response getRolesOfUser(@PathParam("username") String username) {
@ -321,8 +323,9 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for role retrieval.");
}
return Response.status(Response.Status.NOT_FOUND).entity("User by username: " + username +
" does not exist for role retrieval.").build();
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " + username +
" does not exist for role retrieval.").build());
}
} catch (UserStoreException e) {
String msg = "Exception in trying to retrieve roles for user by username: " + username;
@ -340,10 +343,15 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information");
}
List<UserWrapper> userList;
List<UserWrapper> userList, offsetList;
String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter);
int appliedLimit = (limit <= 0) ? -1 : (limit + offset);
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*", -1);
//As the listUsers function accepts limit only to accommodate offset we are passing offset + limit
String[] users = userStoreManager.listUsers(appliedFilter, appliedLimit);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
@ -354,12 +362,24 @@ public class UserManagementServiceImpl implements UserManagementService {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
if (userList.size() <= 0) {
return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build();
if (offset <= userList.size()) {
offsetList = userList.subList(offset, userList.size());
} else {
offsetList = new ArrayList<>();
}
return Response.status(Response.Status.OK).entity(userList).build();
// if (offsetList.size() <= 0) {
// return Response.status(Response.Status.NOT_FOUND).entity("No users available for retrieval").build();
// }
UserList result = new UserList();
result.setList(offsetList);
result.setCount(offsetList.size());
return Response.status(Response.Status.OK).entity(result).build();
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the list of users";
String msg = "ErrorResponse occurred while retrieving the list of users.";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
@ -367,7 +387,7 @@ public class UserManagementServiceImpl implements UserManagementService {
}
@GET
@Path("/usernames")
@Path("/search/usernames")
@Override
public Response getUserNames(@QueryParam("filter") String filter, @HeaderParam("If-Modified-Since") String timestamp,
@QueryParam("offset") int offset, @QueryParam("limit") int limit) {
@ -388,12 +408,12 @@ public class UserManagementServiceImpl implements UserManagementService {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
if (userList.size() <= 0) {
return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build();
}
// if (userList.size() <= 0) {
// return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build();
// }
return Response.status(Response.Status.OK).entity(userList).build();
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the list of users using the filter : " + filter;
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
@ -403,8 +423,8 @@ public class UserManagementServiceImpl implements UserManagementService {
@PUT
@Path("/{username}/credentials")
@Override
public Response resetPassword(@PathParam("username") String username, UserCredentialWrapper credentials) {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials);
public Response resetPassword(@PathParam("username") String username, OldPasswordResetWrapper credentials) {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(username, credentials);
}
}

@ -25,9 +25,11 @@ 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.DeviceList;
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.service.impl.util.*;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.*;
@ -54,22 +56,32 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
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());
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(
"Current logged in user is not authorized to perform this operation").build());
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain));
List<Device> 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();
List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().
getDevicesByNameAndType(name, type, offset, limit);
if (devices == null || devices.size() == 0) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No device, which carries" +
" the name '" + name + "', is currently enrolled in the system").build());
}
return Response.status(Response.Status.OK).entity(devices).build();
// setting up paginated result
DeviceList deviceList = new DeviceList();
deviceList.setList(devices);
deviceList.setCount(devices.size());
return Response.status(Response.Status.OK).entity(deviceList).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the devices that carry the name '" + name + "'";
String msg = "Error occurred at server side while fetching device list.";
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());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}

@ -31,32 +31,32 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
@Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
//@Path("/admin/groups")
//@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_JSON)
public class GroupManagementAdminServiceImpl implements GroupManagementAdminService {
private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class);
@Override
public Response getGroupsOfUser(
@QueryParam("username") String username,
@HeaderParam("If-Modified-Since") String timestamp,
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
try {
PaginationResult result =
DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit);
if (result != null && result.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(result).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
//
// private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class);
//
// @Override
// public Response getGroupsOfUser(
// @QueryParam("username") String username,
// @HeaderParam("If-Modified-Since") String timestamp,
// @QueryParam("offset") int offset,
// @QueryParam("limit") int limit) {
// try {
// PaginationResult result =
// DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit);
// if (result != null && result.getRecordsTotal() > 0) {
// return Response.status(Response.Status.OK).entity(result).build();
// } else {
// return Response.status(Response.Status.NOT_FOUND).build();
// }
// } catch (GroupManagementException e) {
// String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'";
// log.error(msg, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
// }
// }
}

@ -18,7 +18,7 @@
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.UserManagementAdminService;
import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder;
@ -34,8 +34,8 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic
@POST
@Path("/{username}/credentials")
@Override
public Response resetPassword(@PathParam("username") String user, UserCredentialWrapper credentials) {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials);
public Response resetUserPassword(@PathParam("username") String user, PasswordResetWrapper credentials) {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials);
}
}

@ -0,0 +1,40 @@
/*
* 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 java.util.Collections;
import java.util.List;
/**
* This is used instead of filtering from cache.
*/
public class FilteringUtil {
/**
* This is used to filter from the cached policies.
*/
public static <T> List<T> getFilteredList(List<T> sourceList, int offset, int limit) {
if(sourceList == null || sourceList.size() < offset){
return Collections.emptyList();
}
return sourceList.subList(offset, Math.min(offset + limit, sourceList.size()));
}
}

@ -21,10 +21,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
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 org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.*;
import java.util.ArrayList;
import java.util.List;
@ -299,4 +296,20 @@ public class RequestValidationUtil {
}
}
public static void validateCredentials(OldPasswordResetWrapper credentials) {
if (credentials == null || credentials.getNewPassword() == null || credentials.getOldPassword() == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Old or New password " +
"fields cannot be empty").build());
}
}
public static void validateRoleDetails(RoleWrapper roleWrapper) {
if (roleWrapper == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request body is incorrect or" +
" empty").build());
}
}
}

@ -18,15 +18,20 @@
package org.wso2.carbon.device.mgt.jaxrs.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
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.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;
/**
* This class builds Credential modification related Responses
@ -34,55 +39,101 @@ import java.io.UnsupportedEncodingException;
public class CredentialManagementResponseBuilder {
private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class);
private static String PASSWORD_VALIDATION_REGEX_TAG = "PasswordJavaRegEx";
private static String PASSWORD_VALIDATION_ERROR_MSG_TAG = "PasswordJavaRegExViolationErrorMsg";
/**
* Builds the response to change the password of a user
* @param username - Username of the user.
* @param credentials - User credentials
* @return Response Object
*/
public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) {
public static Response buildChangePasswordResponse(String username, OldPasswordResetWrapper credentials) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword());
userStoreManager.updateCredential(credentials.getUsername(), new String(
decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8"));
if (!userStoreManager.isExistingUser(username)) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username "
+ username).build());
}
RequestValidationUtil.validateCredentials(credentials);
if (!validateCredential(credentials.getNewPassword())) {
String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build());
}
userStoreManager.updateCredential(username, credentials.getNewPassword(),
credentials.getOldPassword());
return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
credentials.getUsername() + " was successfully changed.").build();
username + " was successfully changed.").build();
} catch (UserStoreException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.BAD_REQUEST).entity("Old password does not match.").build();
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(e.getMessage()).build());
} catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() +
String msg = "Could not change the password of the user: " + username +
". The Character Encoding is not supported.";
log.error(errorMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
/**
* Builds the response to reset the password of a user
* @param username - Username of the user.
* @param credentials - User credentials
* @return Response Object
*/
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) {
public static Response buildResetPasswordResponse(String username, PasswordResetWrapper credentials) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String(
decodedNewPassword, "UTF-8"));
return Response.status(Response.Status.CREATED).entity("UserImpl password by username: " +
credentials.getUsername() + " was successfully changed.").build();
if (!userStoreManager.isExistingUser(username)) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username "
+ username).build());
}
if (credentials == null || credentials.getNewPassword() == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Password cannot be empty."
+ username).build());
}
if (!validateCredential(credentials.getNewPassword())) {
String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build());
}
userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword());
return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
username + " was successfully changed.").build();
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while updating the credentials of user '" + credentials.getUsername() + "'";
String msg = "ErrorResponse occurred while updating the credentials of user '" + username + "'";
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 (UnsupportedEncodingException e) {
String msg = "Could not change the password of the user: " + credentials.getUsername() +
String msg = "Could not change the password of the user: " + username +
". The Character Encoding 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());
}
}
private static boolean validateCredential(String password)
throws UserStoreException, UnsupportedEncodingException {
String passwordValidationRegex = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_REGEX_TAG);
if (passwordValidationRegex != null) {
Pattern pattern = Pattern.compile(passwordValidationRegex);
if (pattern.matcher(password).matches()) {
return true;
}
}
return false;
}
}

@ -20,14 +20,13 @@ package org.wso2.carbon.device.mgt.jaxrs.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.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
@ -131,6 +130,18 @@ public class DeviceMgtAPIUtils {
return userStoreManager;
}
public static RealmService getRealmService() throws UserStoreException {
RealmService realmService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return realmService;
}
/**
* Getting the current tenant's user realm
*/
@ -237,4 +248,18 @@ public class DeviceMgtAPIUtils {
return gadgetDataService;
}
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
RealmService realmService =
(RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
if (realmService == null) {
throw new IllegalStateException("Realm service has not been initialized.");
}
try {
return realmService.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new DeviceManagementException("Error occured while trying to " +
"obtain tenant id of currently logged in user");
}
}
}

@ -30,98 +30,7 @@
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Activity related APIs -->
<Permission>
<name>Fetch Activity related details</name>
<path>/device-mgt/admin/activities/view</path>
<url>/activities/*</url>
<method>GET</method>
</Permission>
<!-- Activity related APIs -->
<!-- Device related APIs -->
<Permission>
<name>List devices</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices</url>
<method>GET</method>
</Permission>
<Permission>
<name>List device types</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/types</url>
<method>GET</method>
</Permission>
<Permission>
<name>List device types</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/types</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/devices/types</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add User policy</name>
<path>/device-mgt/user/policies/add</path>
<url>/devices/types</url>
<method>GET</method>
</Permission>
<Permission>
<name>Edit policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/devices/types</url>
<method>GET</method>
</Permission>
<Permission>
<name>Edit User policy</name>
<path>/device-mgt/user/policies/update</path>
<url>/devices/types</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/admin/devices/view</path>
<url>/devices/view</url>
<method>GET</method>
</Permission>
<Permission>
<name>View user device</name>
<path>/device-mgt/user/devices/view</path>
<url>/devices/view</url>
<method>GET</method>
</Permission>
<Permission>
<name>Modify user device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/type/*/id/*</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Remove user device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/type/*/id/*</url>
<method>DELETE</method>
</Permission>
<!--Permission Tree Name-->
<Permission>
<name>Device Management</name>
<path>/device-mgt</path>
@ -233,51 +142,90 @@
<url>/</url>
<method>GET</method>
</Permission>
<!--End of Permission Tree-->
<!--<Permission>-->
<!--<name>Get device</name>-->
<!--<path>/device-mgt/devices/view</path>-->
<!--<url>/devices/*/*</url>-->
<!--<method>GET</method>-->
<!--<scope>emm_admin,emm_user</scope>-->
<!--</Permission>-->
<!-- Activity related APIs -->
<Permission>
<name>View device</name>
<path>/device-mgt/admin/devices/view</path>
<url>/devices/user/*/*</url>
<name>Fetch Activity related details</name>
<path>/device-mgt/admin/activities/view</path>
<url>/activities/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>Devices Count All</name>
<name>Fetch Activity related details</name>
<path>/device-mgt/admin/activities/view</path>
<url>/activities</url>
<method>GET</method>
</Permission>
<!-- Activity related APIs -->
<!-- Device related APIs -->
<Permission>
<name>List devices</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/count</url>
<url>/devices</url>
<method>GET</method>
</Permission>
<Permission>
<name>Device Count</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/user/*/count</url>
<name>Retrieve device information</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/*/*/info</url>
<method>GET</method>
</Permission>
<Permission>
<name>List devices</name>
<name>Get device</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/name/*/*</url>
<url>/devices/*/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>List All Own Devices</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/user/*</url>
<name>Get device location</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/*/*/location</url>
<method>GET</method>
</Permission>
<Permission>
<name>devices location</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/locations</url>
<method>POST</method>
</Permission>
<Permission>
<name>Get devices feature</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/*/*/features</url>
<method>GET</method>
</Permission>
<Permission>
<name>Search devices</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/search-devices</url>
<method>POST</method>
</Permission>
<Permission>
<name>list device application</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/*/*/applications</url>
<method>GET</method>
</Permission>
<Permission>
<name>list device operation</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/*/*/operations</url>
<method>GET</method>
</Permission>
<Permission>
<name>list device effective-policy</name>
<path>/device-mgt/admin/devices/list</path>
<url>/devices/*/*/effective-policy</url>
<method>GET</method>
</Permission>
<Permission>
<name>list devices</name>
<path>/device-mgt/admin/devices/list</path>
<url>/admin/devices</url>
<method>GET</method>
</Permission>
<!-- End of Device related APIs -->
<!-- Notification related APIs -->
@ -388,6 +336,20 @@
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/admin/devices/view</path>
<url>/devices/*/*/operations</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/user/devices/view</path>
<url>/devices/*/*/operations</url>
<method>GET</method>
</Permission>
<!--<Permission>-->
<!--<name>Get Applications For Device Type</name>-->
<!--<path>/device-mgt/operations/application/view</path>-->
@ -398,34 +360,61 @@
<!-- End of Operations related APIs -->
<!-- Feature related APIs -->
<!--<Permission>-->
<!--<name>List policies</name>-->
<!--<path>/device-mgt/admin/policies/list</path>-->
<!--<url>/features/*</url>-->
<!--<method>GET</method>-->
<!--</Permission>-->
<!--<Permission>-->
<!--<name>View device</name>-->
<!--<path>/device-mgt/admin/devices/view</path>-->
<!--<url>/features/*</url>-->
<!--<method>GET</method>-->
<!--</Permission>-->
<!--<Permission>-->
<!--<name>View device</name>-->
<!--<path>/device-mgt/user/devices/view</path>-->
<!--<url>/features/*</url>-->
<!--<method>GET</method>-->
<!--</Permission>-->
<!--<Permission>-->
<!--<name>View device</name>-->
<!--<path>/device-mgt/user/devices/view</path>-->
<!--<url>/features</url>-->
<!--<method>GET</method> -->
<!--</Permission>-->
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/features/*</url>
<url>/devices/*/*/features</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/admin/devices/view</path>
<url>/features/*</url>
<url>/devices/*/*/features</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/user/devices/view</path>
<url>/features/*</url>
<url>/devices/*/*/features</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/user/devices/view</path>
<url>/features</url>
<url>/devices/*/*/features</url>
<method>GET</method>
</Permission>
<!-- End of Feature related APIs -->
<!-- Role related APIs -->
@ -460,7 +449,7 @@
<Permission>
<name>List roles</name>
<path>/device-mgt/admin/roles/list</path>
<url>/roles/permissions</url>
<url>/roles/*/permissions</url>
<method>GET</method>
</Permission>
@ -481,22 +470,14 @@
<Permission>
<name>Update role</name>
<path>/device-mgt/admin/roles/update</path>
<url>/roles</url>
<url>/roles/*</url>
<method>PUT</method>
</Permission>
<!--<Permission>-->
<!--<name>Update a specific role</name>-->
<!--<path>/device-mgt/roles/update</path>-->
<!--<url>/roles/*</url>-->
<!--<method>PUT</method>-->
<!---->
<!--</Permission>-->
<Permission>
<name>Update role</name>
<path>/device-mgt/admin/roles/update</path>
<url>/roles/users</url>
<url>/roles/*/users</url>
<method>PUT</method>
</Permission>
@ -510,7 +491,7 @@
<Permission>
<name>Remove role</name>
<path>/device-mgt/admin/roles/remove</path>
<url>/roles</url>
<url>/roles/*</url>
<method>DELETE</method>
</Permission>
@ -529,334 +510,100 @@
<url>/users</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add user</name>
<path>/device-mgt/admin/users/add</path>
<url>/users</url>
<method>POST</method>
</Permission>
<Permission>
<name>View user</name>
<path>/device-mgt/admin/users/view</path>
<url>/users/view</url>
<name>List users</name>
<path>/device-mgt/admin/users/list</path>
<url>/users/search/usernames</url>
<method>GET</method>
</Permission>
<Permission>
<name>Update user</name>
<path>/device-mgt/admin/users/update</path>
<name>Add user</name>
<path>/device-mgt/admin/users/add</path>
<url>/users</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Change user password</name>
<path>/login</path>
<url>/users/change-password</url>
<method>POST</method>
</Permission>
<Permission>
<name>Reset password</name>
<path>/device-mgt/admin/users/password-reset</path>
<url>/users/reset-password</url>
<method>POST</method>
</Permission>
<Permission>
<name>Remove user</name>
<path>/device-mgt/admin/users/remove</path>
<url>/users</url>
<url>/users/*</url>
<method>DELETE</method>
</Permission>
<Permission>
<name>View user</name>
<path>/device-mgt/admin/users/view</path>
<url>/users/roles</url>
<url>/users/*</url>
<method>GET</method>
</Permission>
<!--<Permission>-->
<!--<name>Get user roles by name</name>-->
<!--<path>/device-mgt/admin/users/view</path>-->
<!--<url>/roles</url>-->
<!--<method>GET</method>-->
<!--</Permission>-->
<Permission>
<name>Add user</name>
<path>/device-mgt/admin/users/add</path>
<url>/roles</url>
<method>POST</method>
</Permission>
<Permission>
<name>List user devices</name>
<path>/device-mgt/user/devices/list</path>
<url>/users/devices</url>
<method>GET</method>
</Permission>
<Permission>
<name>View user</name>
<path>/device-mgt/admin/users/view</path>
<url>/users/*/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>List users</name>
<path>/device-mgt/admin/users/list</path>
<url>/users/count</url>
<method>GET</method>
<name>Update user</name>
<path>/device-mgt/admin/users/update</path>
<url>/users/*</url>
<method>PUT</method>
</Permission>
<Permission>
<name>List users</name>
<path>/device-mgt/admin/users/list</path>
<url>/users/view-users</url>
<method>GET</method>
<name>Update user credential</name>
<path>/device-mgt/admin/users/update</path>
<url>/users/*/credentials</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Add role</name>
<name>Get role</name>
<path>/device-mgt/admin/roles/add</path>
<url>/users/view-users</url>
<method>GET</method>
</Permission>
<Permission>
<name>Update role</name>
<path>/device-mgt/admin/roles/update</path>
<url>/users/view-users</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/users/view-users</url>
<method>GET</method>
</Permission>
<Permission>
<name>Update policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/users/view-users</url>
<method>GET</method>
</Permission>
<Permission>
<name>List users</name>
<path>/device-mgt/admin/users/list</path>
<url>/users/users-by-username</url>
<method>GET</method>
</Permission>
<Permission>
<name>List users</name>
<path>/device-mgt/admin/users/list</path>
<url>/users/users-by-username/*</url>
<url>/users/*/roles</url>
<method>GET</method>
</Permission>
<Permission>
<name>Invite user</name>
<path>/device-mgt/admin/users/invite</path>
<url>/users/email-invitation</url>
<name>Update user credential</name>
<path>/device-mgt/admin/users/update</path>
<url>/admin/users/*/credentials</url>
<method>POST</method>
</Permission>
<Permission>
<name>Authorize user</name>
<path>/login</path>
<url>/users/authorize</url>
<method>POST</method>
</Permission>
<!-- End of User related APIs -->
<!-- Policy related APIs -->
<Permission>
<name>Add Policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/inactive-policy</url>
<method>POST</method>
</Permission>
<Permission>
<name>Add Policy</name>
<path>/device-mgt/user/policies/add</path>
<url>/policies/inactive-policy</url>
<method>POST</method>
</Permission>
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/policies/*/*</url>
<method>POST</method>
</Permission>
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/policies/*/*/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/admin/devices/view</path>
<url>/policies/*/*/*</url>
<url>/policies</url>
<method>GET</method>
</Permission>
<Permission>
<name>View device</name>
<path>/device-mgt/user/devices/view</path>
<url>/policies/*/*/*</url>
<method>GET</method>
<name>Add Policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies</url>
<method>POST</method>
</Permission>
<Permission>
<name>Add policy</name>
<name>Activate policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/active-policy</url>
<method>POST</method>
<url>/policies/activate-policy</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Add Policy</name>
<name>Deactivate Policy</name>
<path>/device-mgt/user/policies/add</path>
<url>/policies/inactive-policy</url>
<method>POST</method>
<url>/policies/deactivate-policy</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Remove policy</name>
<path>/device-mgt/admin/policies/remove</path>
<url>/policies/bulk-remove</url>
<name>Remove Policy</name>
<path>/device-mgt/user/policies/remove</path>
<url>/policies/remove-policy</url>
<method>POST</method>
</Permission>
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/policies</url>
<method>GET</method>
</Permission>
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/policies/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>List user policies</name>
<path>/device-mgt/user/policies/list</path>
<url>/policies</url>
<method>GET</method>
</Permission>
<Permission>
<name>List user policies</name>
<path>/device-mgt/user/policies/list</path>
<name>View Policy</name>
<path>/device-mgt/admin/policies/view</path>
<url>/policies/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>Update policy</name>
<name>Update Policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/policies/*</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Remove policy</name>
<path>/device-mgt/admin/policies/remove</path>
<url>/policies</url>
<method>DELETE</method>
</Permission>
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/policies/count</url>
<method>GET</method>
</Permission>
<Permission>
<name>Edit policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/policies/priorities</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Edit policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/policies/activate</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/activate</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Edit policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/policies/inactivate</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/inactivate</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Edit policy</name>
<path>/device-mgt/admin/policies/update</path>
<url>/policies/apply-changes</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/start-task/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/update-task/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add policy</name>
<path>/device-mgt/admin/policies/add</path>
<url>/policies/stop-task</url>
<method>GET</method>
</Permission>
<Permission>
<name>List policies</name>
<path>/device-mgt/admin/policies/list</path>
<url>/policies/*/*</url>
<method>GET</method>
<method>Put</method>
</Permission>
<!-- End of Policy related APIs -->
@ -893,9 +640,9 @@
</Permission>
<Permission>
<name>Device Information</name>
<name>Get additional information of devices</name>
<path>/device-mgt/admin/information/list</path>
<url>/information/list</url>
<url>/devices/get-info</url>
<method>POST</method>
</Permission>
@ -939,14 +686,6 @@
<url>/configuration</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add configuration</name>
<path>/device-mgt/admin/platform-configs/add</path>
<url>/configuration</url>
<method>POST</method>
</Permission>
<Permission>
<name>Update configuration</name>
<path>/device-mgt/admin/platform-configs/modify</path>
@ -1236,5 +975,4 @@
<method>GET</method>
</Permission>
<!-- End of Dashboard related APIs -->
</PermissionConfiguration>

@ -55,6 +55,7 @@
<property name="resourcePackage" value="org.wso2.carbon.device.mgt.jaxrs"/>
<property name="version" value="1.0"/>
<property name="host" value="localhost:9443"/>
<property name="schemes" value="https" />
<property name="basePath" value="/api/device-mgt/v1.0"/>
<property name="title" value="Device Management Admin Service API Definitions"/>
<property name="contact" value="dev@wso2.org"/>

@ -26,11 +26,11 @@ import io.swagger.annotations.ApiModelProperty;
+ " responses")
public class OperationResponse {
@ApiModelProperty(name = "response", value = "Operation response return from the device", required = true)
@ApiModelProperty(name = "response", value = "Operation response returned from the device", required = true)
private String response;
@ApiModelProperty(name = "recievedTimeStamp", value = "Time that the operation response received",
@ApiModelProperty(name = "receivedTimeStamp", value = "Time that the operation response received",
required = true)
private String recievedTimeStamp;
private String receivedTimeStamp;
public String getResponse() {
return response;
@ -40,12 +40,12 @@ public class OperationResponse {
this.response = response;
}
public String getRecievedTimeStamp() {
return recievedTimeStamp;
public String getReceivedTimeStamp() {
return receivedTimeStamp;
}
public void setRecievedTimeStamp(String recievedTimeStamp) {
this.recievedTimeStamp = recievedTimeStamp;
public void setReceivedTimeStamp(String receivedTimeStamp) {
this.receivedTimeStamp = receivedTimeStamp;
}
}

@ -259,7 +259,8 @@ public interface DeviceDAO {
* @return returns list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException;
List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException;
/**
* This method is used to retrieve devices of a given device name as a paginated result.

@ -619,47 +619,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
return deviceCount;
}
/**
* Get the list of devices that matches with the given device name.
*
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @return device list
* @throws DeviceManagementDAOException
*/
@Override
public List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>();
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceName + "%");
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " +
"'" + deviceName + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return devices;
}
@Override
public int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException {
Connection conn;

@ -303,6 +303,71 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
/**
* Get the list of devices that matches with the given device name and (or) device type.
*
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @return device list
* @throws DeviceManagementDAOException
*/
@Override
public List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException {
String filteringString = "";
if (deviceName != null && !deviceName.isEmpty()) {
filteringString = filteringString + " AND d.NAME LIKE ?";
}
if (type != null && !type.isEmpty()) {
filteringString = filteringString + " AND t.NAME = ?";
}
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>();
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID LIMIT ?, ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
int i = 1;
if (deviceName != null && !deviceName.isEmpty()) {
stmt.setString(++i, deviceName + "%");
}
if (type != null && !type.isEmpty()) {
stmt.setString(++i, type);
}
stmt.setInt(++i, offset);
stmt.setInt(++i, limit);
rs = stmt.executeQuery();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return devices;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -310,6 +310,71 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
/**
* Get the list of devices that matches with the given device name and (or) device type.
*
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @return device list
* @throws DeviceManagementDAOException
*/
@Override
public List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException {
String filteringString = "";
if (deviceName != null && !deviceName.isEmpty()) {
filteringString = filteringString + " AND d.NAME LIKE ?";
}
if (type != null && !type.isEmpty()) {
filteringString = filteringString + " AND t.NAME = ?";
}
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>();
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"(SELECT d.ID, d.NAME, d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID) rs) WHERE offset >= ? AND ROWNUM <= ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
int i = 1;
if (deviceName != null && !deviceName.isEmpty()) {
stmt.setString(++i, deviceName + "%");
}
if (type != null && !type.isEmpty()) {
stmt.setString(++i, type);
}
stmt.setInt(++i, offset);
stmt.setInt(++i, limit);
rs = stmt.executeQuery();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return devices;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -303,6 +303,71 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
/**
* Get the list of devices that matches with the given device name and (or) device type.
*
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @return device list
* @throws DeviceManagementDAOException
*/
@Override
public List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException {
String filteringString = "";
if (deviceName != null && !deviceName.isEmpty()) {
filteringString = filteringString + " AND d.NAME LIKE ?";
}
if (type != null && !type.isEmpty()) {
filteringString = filteringString + " AND t.NAME = ?";
}
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>();
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? LIMIT ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
int i = 1;
if (deviceName != null && !deviceName.isEmpty()) {
stmt.setString(++i, deviceName + "%");
}
if (type != null && !type.isEmpty()) {
stmt.setString(++i, type);
}
stmt.setInt(++i, offset);
stmt.setInt(++i, limit);
rs = stmt.executeQuery();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return devices;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -305,6 +305,71 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
/**
* Get the list of devices that matches with the given device name and (or) device type.
*
* @param deviceName Name of the device.
* @param tenantId Id of the current tenant
* @return device list
* @throws DeviceManagementDAOException
*/
@Override
public List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException {
String filteringString = "";
if (deviceName != null && !deviceName.isEmpty()) {
filteringString = filteringString + " AND d.NAME LIKE ?";
}
if (type != null && !type.isEmpty()) {
filteringString = filteringString + " AND t.NAME = ?";
}
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>();
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
int i = 1;
if (deviceName != null && !deviceName.isEmpty()) {
stmt.setString(++i, deviceName + "%");
}
if (type != null && !type.isEmpty()) {
stmt.setString(++i, type);
}
stmt.setInt(++i, offset);
stmt.setInt(++i, limit);
rs = stmt.executeQuery();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return devices;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -207,7 +207,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
while (rs.next()) {
OperationResponse response = new OperationResponse();
response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
byte[] contentBytes;
@ -435,7 +435,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
ClassNotFoundException, IOException, SQLException {
OperationResponse response = new OperationResponse();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
}
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;

@ -139,7 +139,7 @@ public interface DeviceManagementProviderService {
* @throws DeviceManagementException If some unusual behaviour is observed while fetching the
* device list
*/
List<Device> getDevicesByName(String deviceName) throws DeviceManagementException;
List<Device> getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException;
/**
* This method is used to retrieve list of devices that matches with the given device name with paging information.

@ -31,11 +31,7 @@ import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
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.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
@ -50,13 +46,7 @@ import org.wso2.carbon.email.sender.core.TypedValue;
import org.wso2.carbon.user.api.UserStoreException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService,
PluginInitializationListener {
@ -1062,12 +1052,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
@Override
public List<Device> getDevicesByName(String deviceName) throws DeviceManagementException {
public List<Device> getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException {
List<Device> devices = new ArrayList<>();
List<Device> allDevices;
try {
DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesByName(deviceName, this.getTenantId());
allDevices = deviceDAO.getDevicesByNameAndType(deviceName, type, this.getTenantId(), offset, limit);
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '"
+ deviceName + "'", e);
@ -1240,7 +1230,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return CarbonContext.getThreadLocalCarbonContext().getTenantId();
}
// private int getTenantId(String tenantDomain) throws DeviceManagementException {
// RealmService realmService =
// (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
// if (realmService == null) {
// throw new IllegalStateException("");
// }
// try {
// return realmService.getTenantManager().getTenantId(tenantDomain);
// } catch (UserStoreException e) {
// throw new DeviceManagementException("");
// }
// }
private DeviceManager getDeviceManager(String deviceType) {
DeviceManagementService deviceManagementService =
pluginRepository.getDeviceManagementService(deviceType, this.getTenantId());
if (deviceManagementService == null) {

@ -59,7 +59,7 @@
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps
</outputDirectory>
<destFileName>admin-certificate.war</destFileName>
<destFileName>api#certificate-mgt#v1.0.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>

@ -1,2 +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);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/api#certificate-mgt#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#certificate-mgt#v1.0.war,overwrite:true);\
Loading…
Cancel
Save