Merging rest-api-improvements branch to master

revert-70aa11f8
prabathabey 9 years ago
commit aeb4ad3295

@ -49,7 +49,8 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance()
.isPublished()) {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);

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

@ -1,9 +1,17 @@
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 javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/scep")
public interface CertificateMgtService {
/**
@ -13,8 +21,37 @@ 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>

@ -253,10 +253,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;

@ -17,7 +17,6 @@
*/
package org.wso2.carbon.certificate.mgt.core.service;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
@ -33,7 +32,6 @@ import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import java.io.InputStream;
import java.security.PrivateKey;
@ -173,7 +171,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) {

@ -46,7 +46,7 @@
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>devicemgt_admin</warName>
<warName>api#device-mgt#v1.0</warName>
</configuration>
</plugin>
</plugins>
@ -72,7 +72,7 @@
<tasks>
<copy todir="${basedir}/../../../repository/deployment/server/webapps" overwrite="true">
<fileset dir="${basedir}/target">
<include name="devicemgt_admin.war" />
<include name="api#device-mgt#v1.0.war" />
</fileset>
</copy>
</tasks>
@ -243,6 +243,11 @@
<artifactId>org.wso2.carbon.device.mgt.analytics.dashboard</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
@ApiModel(value = "NotificationContext")
public class NotificationContext {
private DeviceIdentifier deviceId;
private Notification notification;
public NotificationContext(DeviceIdentifier deviceId, Notification notification) {
this.deviceId = deviceId;
this.notification = notification;
}
@ApiModelProperty(value = "deviceId")
@JsonProperty("deviceId")
public DeviceIdentifier getDeviceId() {
return deviceId;
}
public void setDeviceId(DeviceIdentifier deviceId) {
this.deviceId = deviceId;
}
@ApiModelProperty(value = "notification")
@JsonProperty("notification")
public Notification getNotification() {
return notification;
}
public void setNotification(Notification notification) {
this.notification = notification;
}
}

@ -0,0 +1,106 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import java.util.ArrayList;
import java.util.List;
@ApiModel(value = "Notifications")
public class NotificationList {
private int count;
private String next;
private String previous;
private List<Notification> notifications = new ArrayList<>();
/**
* Number of notifications returned.
*/
@ApiModelProperty(value = "Number of Devices returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
/**
**/
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices")
public List<Notification> getList() {
return notifications;
}
public void setList(List<Notification> notifications) {
this.notifications = notifications;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(count).append(",\n");
sb.append(" next: ").append(next).append(",\n");
sb.append(" previous: ").append(previous).append(",\n");
sb.append(" notifications: [").append(notifications).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -1,151 +0,0 @@
/*
* 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.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.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* All the certificate related tasks such as saving certificates, can be done through this endpoint.
*/
@API(name = "Certificate", version = "1.0.0", context = "/devicemgt_admin/certificates", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Api(value = "Certificate", description = "Certificate related tasks such as saving certificates, " +
"can be done through this API")
@SuppressWarnings("NonJaxWsWebServices")
@Path("/certificates")
@Produces({ "application/json", "application/xml" })
@Consumes({ "application/json", "application/xml" })
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;
}

@ -1,91 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* General Tenant Configuration REST-API implementation.
* All end points support JSON, XMl with content negotiation.
*/
@API(name = "Configuration", version = "1.0.0", context = "/devicemgt_admin/configuration", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/configuration")
@Api(value = "Configuration", description = "General Tenant Configuration management capabilities are exposed " +
"through this API")
@SuppressWarnings("NonJaxWsWebServices")
@Produces({ "application/json", "application/xml" })
@Consumes({ "application/json", "application/xml" })
public interface Configuration {
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "POST",
value = "Configuring general platform settings",
notes = "Configure the general platform settings using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Tenant configuration saved successfully"),
@ApiResponse(code = 500, message = "Error occurred while saving the tenant configuration")
})
@Permission(scope = "configuration-modify", permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"})
Response saveTenantConfiguration(@ApiParam(name = "configuration", value = "The required properties to "
+ "update the platform configurations the as the <JSON_PAYLOAD> value",
required = true) PlatformConfiguration configuration);
@GET
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting General Platform Configurations",
notes = "Get the general platform level configuration details using this REST API",
response = PlatformConfiguration.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the tenant configuration")
})
@Permission(scope = "configuration-view", permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"})
Response getConfiguration();
@PUT
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "PUT",
value = "Updating General Platform Configurations",
notes = "Update the notification frequency using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Tenant configuration updated successfully"),
@ApiResponse(code = 500, message = "Error occurred while updating the tenant configuration")
})
@Permission(scope = "configuration-modify", permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"})
Response updateConfiguration(@ApiParam(name = "configuration", value = "The required properties to update"
+ " the platform configurations the as the <JSON_PAYLOAD> value",
required = true) PlatformConfiguration configuration);
}

@ -1,81 +0,0 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.Api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("/dashboard")
@Api(value = "Dashboard", description = "Dashboard related operations are described here.")
@SuppressWarnings("NonJaxWsWebServices")
public interface Dashboard {
String CONNECTIVITY_STATUS = "connectivity-status";
String POTENTIAL_VULNERABILITY = "potential-vulnerability";
String NON_COMPLIANT_FEATURE_CODE = "non-compliant-feature-code";
String PLATFORM = "platform";
String OWNERSHIP = "ownership";
// Constants related to pagination
String PAGINATION_ENABLED = "pagination-enabled";
String START_INDEX = "start";
String RESULT_COUNT = "length";
@GET
@Path("device-count-overview")
Response getOverviewDeviceCounts();
@GET
@Path("device-counts-by-potential-vulnerabilities")
Response getDeviceCountsByPotentialVulnerabilities();
@GET
@Path("non-compliant-device-counts-by-features")
Response getNonCompliantDeviceCountsByFeatures(@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount);
@GET
@Path("device-counts-by-groups")
Response getDeviceCountsByGroups(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership);
@GET
@Path("feature-non-compliant-device-counts-by-groups")
Response getFeatureNonCompliantDeviceCountsByGroups(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership);
@GET
@Path("filtered-device-count-over-total")
Response getFilteredDeviceCountOverTotal(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership);
@GET
@Path("feature-non-compliant-device-count-over-total")
Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership);
@GET
@Path("devices-with-details")
Response getDevicesWithDetails(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership,
@QueryParam(PAGINATION_ENABLED) String paginationEnabled,
@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount);
@GET
@Path("feature-non-compliant-devices-with-details")
Response getFeatureNonCompliantDevicesWithDetails(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership,
@QueryParam(PAGINATION_ENABLED) String paginationEnabled,
@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount);
}

@ -1,213 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Device related operations such as get all the available devices, etc.
*/
@API(name = "Device", version = "1.0.0", context = "/devicemgt_admin/devices", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/devices")
@Api(value = "Device", description = "Device related operations such as get all the available devices, etc.")
@SuppressWarnings("NonJaxWsWebServices")
public interface Device {
/**
* Get all devices. We have to use accept all the necessary query parameters sent by datatable.
* Hence had to put lot of query params here.
*
* @return Device List
*/
@GET
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Returns device list",
notes = "Returns the set of devices that matches a given device type, user, role, "
+ "enrollment status, ownership type",
response = org.wso2.carbon.device.mgt.common.Device.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of Devices"),
@ApiResponse(code = 500, message = "Error occurred while fetching the device list")
})
@Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getAllDevices(@ApiParam(name = "type", value = "Provide the device type, such as ios, android or"
+ " windows", required = true) @QueryParam("type") String type,
@ApiParam(name = "user", value = "Get the details of the devices registered to a "
+ "user by providing the user name", required = true) @QueryParam("user")
String user,
@ApiParam(name = "role", value = "Get the details of the devices registered to a "
+ "specific role by providing the role name", required = true)
@QueryParam("role") String role,
@ApiParam(name = "status", value = "Provide the device status details, such as "
+ "active or inactive", required = true) @QueryParam("status")
EnrolmentInfo.Status status,
@ApiParam(name = "start", value = "Provide the starting pagination index",
required = true) @QueryParam("start") int startIdx,
@ApiParam(name = "length", value = "Provide how many device details you require "
+ "from the starting pagination index", required = true)
@QueryParam("length") int length,
@ApiParam(name = "device-name", value = "Provide the name of a registered device "
+ "and receive the specified device details", required = true)
@QueryParam("device-name") String deviceName,
@ApiParam(name = "ownership", value = "Provide the device ownership type and "
+ "receive the specific device details", required = true)
@QueryParam("ownership") EnrolmentInfo.OwnerShip ownership);
/**
* Fetch device details for a given device type and device Id.
*
* @return Device wrapped inside Response
*/
@GET
@Path("view")
@Produces({ MediaType.APPLICATION_JSON })
@Permission(scope = "device-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getDevice(@QueryParam("type") String type, @QueryParam("id") String id);
/**
* Fetch device details of a given user.
*
* @param user User Name
* @return Device
*/
@GET
@Path("user/{user}")
@Permission(scope = "device-view-own", permissions = {
"/permission/admin/device-mgt/user/devices/list",
"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceOfUser(@PathParam("user") String user);
/**
* Fetch device count of a given user.
*
* @param user User Name
* @return Device
*/
@GET
@Path("user/{user}/count")
@Permission(scope = "device-view-own", permissions = {
"/permission/admin/device-mgt/user/devices/list",
"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceCountOfUser(@PathParam("user") String user);
/**
* Get current device count
*
* @return device count
*/
@GET
@Path("count")
@ApiOperation(
httpMethod = "GET",
value = "Getting the Device Count",
notes = "Get the number of devices that are registered with WSO2 EMM.",
response = int.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Device count"),
@ApiResponse(code = 500, message = "Error occurred while fetching the device count")
})
@Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceCount();
/**
* Get the list of devices that matches with the given name.
*
* @param deviceName Device name
* @param tenantDomain Callee tenant domain
* @return list of devices.
*/
@GET
@Path("name/{name}/{tenantDomain}")
@ApiOperation(
httpMethod = "GET",
value = "Get the device details of a specific device via the REST API",
notes = "Get the device details of a specific device",
response = DeviceType.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of devices"),
@ApiResponse(code = 500, message = "Error occurred while fetching the devices list of device name")
})
@Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDevicesByName(@ApiParam(name = "name", value = "The name of the device or windows", required = true)
@PathParam("name") String deviceName,
@ApiParam(name = "tenantDomain", value = "Tenant domain name. The default "
+ "tenant domain of WSO2 EMM is carbon.super", required = true)
@PathParam("tenantDomain") String tenantDomain);
/**
* Get the list of available device types.
*
* @return list of device types.
*/
@GET
@Path("types")
@ApiOperation(
httpMethod = "GET",
value = "Getting Details of the Devices Supported via WSO2 EMM",
notes = "You are able to register Android, iOS and Windows devices with WSO2 EMM. This API will "
+ "retrieve the device type details that can register with the EMM",
response = DeviceType.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of devices based on the type"),
@ApiResponse(code = 500, message = "Error occurred while fetching the list of device types") })
@Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/user/devices/list"})
Response getDeviceTypes();
/**
* Update device.
*
* @return update status.
*/
@PUT
@Path("type/{type}/id/{deviceId}")
@Permission(scope = "device-modify", permissions = {
"/permission/admin/device-mgt/user/devices/modify", "/permission/admin/device-mgt/admin/devices/modify"})
Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId,
org.wso2.carbon.device.mgt.common.Device updatedDevice);
/**
* disenroll device.
*
* @return disenrollment status.
*/
@DELETE
@Path("type/{type}/id/{deviceId}")
@Permission(scope = "device-modify", permissions = {
"/permission/admin/device-mgt/user/devices/modify", "/permission/admin/device-mgt/admin/devices/modify"})
Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId);
}

@ -1,152 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Device information related operations.
*/
@API(name = "Device Information", version = "1.0.0", context = "/devicemgt_admin/information", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/information")
@Api(value = "DeviceInformation", description = "Device information related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
public interface DeviceInformation {
@GET
@Path("{type}/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get device information",
notes = "This will return device information such as CPU usage, memory usage etc.",
response = DeviceInfo.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceInfo(@ApiParam(name = "type", value = "Provide the device type, such as ios, android "
+ "or windows", required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Provide the device identifier", required = true)
@PathParam("id") String id);
@POST
@Path("list")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Get 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")
@ApiResponses(value = {
@ApiResponse(code = 200, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDevicesInfo(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers",
required = true) List<DeviceIdentifier> deviceIdentifiers);
@GET
@Path("location/{type}/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the device location",
notes = "This will return the device location including latitude and longitude as well the "
+ "physical address",
response = DeviceLocation.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceLocation(@ApiParam(name = "type", value = "Provide the device type, such as ios, "
+ "android or windows", required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Provide the device identifier",
required = true) @PathParam("id") String id);
@GET
@Path("location/list")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the locations of devices",
notes = "This will return the locations of devices including latitude and longitude as well the "
+ "physical address for the supplied device identifiers",
response = DeviceLocation.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceLocations(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers",
required = true) List<DeviceIdentifier> deviceIdentifiers);
@GET
@Path("application/{type}/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the device applications",
notes = "This will return the device applications including their memory usages.",
response = Application.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 400, message = ""),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceApplications(@ApiParam(name = "type", value = "Provide the device type, such as ios, "
+ "android or windows", required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Provide the device identifier",
required = true) @PathParam("id") String id);
}

@ -1,122 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* DeviceNotification management REST-API implementation.
* All end points support JSON, XMl with content negotiation.
*/
@API(name = "Device Notification", version = "1.0.0", context = "/devicemgt_admin/notifications", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Api(value = "DeviceNotification", description = "Device notification related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
@Path("/notifications")
@Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"})
public interface DeviceNotification {
@GET
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting all Device Notification Details",
notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using "
+ "this REST API",
response = Notification.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of Notifications", response = Notification.class,
responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the notification list")
})
@Permission(scope = "device-notification-view", permissions = {
"/permission/admin/device-mgt/admin/notifications/view",
"/permission/admin/device-mgt/user/notifications/view"})
Response getNotifications();
@GET
@Path("{status}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting the Device Notifications Filtered by the Status",
notes = "Get the details of all the unread notifications or the details of all the read "
+ "notifications using this REST API",
response = Notification.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of Notifications", response = Notification.class,
responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the notification list")
})
@Permission(scope = "device-notification-view", permissions = {
"/permission/admin/device-mgt/admin/notifications/view",
"/permission/admin/device-mgt/user/notifications/view"})
Response getNotificationsByStatus(@ApiParam(name = "status", value = "Provide the notification status as"
+ " the value for {status}", required = true)
@PathParam("status") Notification.Status status);
@PUT
@Path("{id}/{status}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "PUT",
value = "Updating the Device Notification Status",
notes = "When a user has read the the device notification the device notification status must "
+ "change from NEW to CHECKED. Update the device notification status using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Notification status updated successfully"),
@ApiResponse(code = 500, message = "Error occurred while updating notification status")
})
@Permission(scope = "device-notification-modify",
permissions = {"/permission/admin/device-mgt/admin/notifications/modify"})
Response updateNotificationStatus(@ApiParam(name = "id", value = "Provide the ID of the notification"
+ " you wish you update", required = true) @PathParam("id") int id,
@ApiParam(name = "status", value = "Provide the notification status as"
+ " the value", required = true) @PathParam("status")
Notification.Status status);
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "POST",
value = "Sending a Device Notification",
notes = "Notify users on device operation failures and other information using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Notification has been added successfully"),
@ApiResponse(code = 500, message = "Error occurred while updating notification status")
})
@Permission(scope = "device-notification-modify",
permissions = {"/permission/admin/device-mgt/admin/notifications/modify"})
Response addNotification(Notification notification);
}

@ -1,76 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Device search related operations such as getting device information.
*/
@API(name = "Device Search", version = "1.0.0", context = "/devicemgt_admin/search", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/search")
@Api(value = "DeviceSearch", description = "Device searching related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
public interface DeviceSearch {
@GET
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Advanced Search for Devices via the Console",
notes = "Carry out an advanced search via the EMM console",
response = DeviceWrapper.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = DeviceWrapper.class, responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while searching the device information")
})
@Permission(scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDeviceInfo(@ApiParam(name = "enrollmentCertificates", value = "List of search conditions",
required = true) SearchContext searchContext);
@GET
@Path("after/{time}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get devices information since a specified time.",
notes = "Get devices information of devices updated since a specified time.",
response = DeviceWrapper.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = DeviceWrapper.class, responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while fetching the device information")
})
@Permission(scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/update-since-list"})
Response getUpdatedDevices(@ApiParam(name = "time", value = "Time since the updated devices should be " +
"fetched.", required = true)@PathParam("time") String time);
}

@ -1,66 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Features
*/
@API(name = "Feature", version = "1.0.0", context = "/devicemgt_admin/features", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Api(value = "Feature", description = "Feature management related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
@Path("/features")
@Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"})
public interface Feature {
/**
* Get all features for Mobile Device Type
*
* @return Feature
*/
@GET
@Path("/{type}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Get Feature Details of a Device",
notes = "WSO2 EMM features enable you to carry out many operations on a given device platform. " +
"Using this REST API you can get the features that can be carried out on a preferred device type," +
" such as iOS, Android or Windows.",
response = org.wso2.carbon.device.mgt.common.Feature.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of Features"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of features" +
".") })
@Permission(scope = "feature-view", permissions = {"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getFeatures(@ApiParam(name = "type", value = "Provide the device type, such as ios, android or windows",
required = true) @PathParam("type") String type);
}

@ -1,198 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.Api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.List;
@API(name = "Group", version = "1.0.0", context = "/devicemgt_admin/groups", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/groups")
@Api(value = "Group", description = "Group related operations such as get all the available groups, etc.")
@SuppressWarnings("NonJaxWsWebServices")
public interface Group {
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getGroups(@QueryParam("start") int startIndex, @QueryParam("length") int length);
@POST
@Consumes("application/json")
@Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/user/groups/add"})
Response createGroup(DeviceGroup group);
@Path("/owner/{owner}/name/{groupName}")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/view"})
Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
@Path("/owner/{owner}/name/{groupName}")
@PUT
@Consumes("application/json")
@Produces("application/json")
@Permission(scope = "group-modify", permissions = {"/permission/admin/device-mgt/user/groups/update"})
Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
DeviceGroup deviceGroup);
@Path("/owner/{owner}/name/{groupName}")
@DELETE
@Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/user/groups/remove"})
Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
@Path("/all")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getAllGroups();
@Path("/user/{user}")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex,
@QueryParam("length") int length);
@Path("/user/{user}/search")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response findGroups(@QueryParam("groupName") String groupName, @PathParam("user") String user);
@Path("/user/{user}/all")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getGroups(@PathParam("user") String userName, @QueryParam("permission") String permission);
@Path("/count")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getAllGroupCount();
@Path("/user/{user}/count")
@GET
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getGroupCount(@PathParam("user") String userName);
@Path("/owner/{owner}/name/{groupName}/share")
@PUT
@Produces("application/json")
@Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/share"})
Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@FormParam("shareUser") String shareUser, @FormParam("roleName") String sharingRole);
@Path("/owner/{owner}/name/{groupName}/unshare")
@PUT
@Produces("application/json")
@Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/unshare"})
Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@FormParam("unShareUser") String unShareUser,
@FormParam("roleName") String sharingRole);
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
@PUT
@Produces("application/json")
@Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/admin/groups/roles/permissions/add"})
Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("roleName") String roleName, String[] permissions);
@DELETE
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
@Produces("application/json")
@Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/admin/groups/roles/permissions/remove"})
Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("roleName") String roleName);
@GET
@Path("/owner/{owner}/name/{groupName}/share/roles")
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/admin/groups/roles"})
Response getRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@QueryParam("userName") String userName);
@PUT
@Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles")
@Produces("application/json")
@Permission(scope = "group-modify", permissions = {"/permission/admin/device-mgt/admin/groups/roles"})
Response setRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("userName") String userName, List<String> selectedRoles);
@GET
@Path("/owner/{owner}/name/{groupName}/users")
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getUsers(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
@GET
@Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/admin/groups/roles"})
Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@QueryParam("start") int startIdx, @QueryParam("length") int length);
@GET
@Path("/owner/{owner}/name/{groupName}/devices/count")
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/devices/count"})
Response getDeviceCount(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
@POST
@Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json")
@Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/user/groups/devices/add"})
Response addDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
DeviceIdentifier deviceIdentifier);
@DELETE
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}")
@Produces("application/json")
@Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/user/groups/devices/remove"})
Response removeDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("deviceId") String deviceId, @PathParam("deviceType") String deviceType);
@GET
@Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions")
@Produces("application/json")
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/roles/permissions"})
Response getPermissions(@PathParam("userName") String userName, @PathParam("groupName") String groupName,
@PathParam("owner") String owner);
}

@ -1,66 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.Api;
import org.wso2.carbon.apimgt.annotations.api.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This class represents license related operations.
*/
@API(name = "License", version = "1.0.0", context = "/devicemgt_admin/license", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Api(value = "License")
@Path("/license")
@SuppressWarnings("NonJaxWsWebServices")
public interface License {
/**
* This method returns the license text related to a given device type and language code.
*
* @param deviceType Device type, ex: android, ios
* @param languageCode Language code, ex: en_US
* @return Returns the license text
*/
@GET
@Path("{deviceType}/{languageCode}")
@Produces({ MediaType.APPLICATION_JSON })
@Permission(scope = "license-view", permissions = {"/permission/admin/device-mgt/admin/device/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getLicense(@PathParam("deviceType") String deviceType,
@PathParam("languageCode") String languageCode);
/**
* This method is used to add license to a specific device type.
*
* @param deviceType Device type, ex: android, ios
* @param license License object
* @return Returns the acknowledgement for the action
*/
@POST
@Path("{deviceType}")
@Permission(scope = "license-add", permissions = {"/permission/admin/device-mgt/admin/devices/view"})
Response addLicense(@PathParam("deviceType") String deviceType,
org.wso2.carbon.device.mgt.common.license.mgt.License license);
}

@ -1,215 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
*/
@API(name = "Operation", version = "1.0.0", context = "/devicemgt_admin/operations", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/operations")
@Api(value = "Operation", description = "Operation management related operations can be found here.")
public interface Operation {
/* @deprecated */
@GET
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getAllOperations();
@GET
@Path("paginate/{type}/{id}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting Paginated Details for Operations on a Device.",
notes = "You will carry out many operations on a device. In a situation where you wish to view the all" +
" the operations carried out on a device it is not feasible to show all the details on one page" +
" therefore the details are paginated." +
" Example: You carry out 21 operations via a given device. When you wish to see the operations " +
"carried out, the details of the 21 operations will be broken down into 3 pages with 10 operation" +
" details per page.",
response = org.wso2.carbon.device.mgt.common.operation.mgt.Operation.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "List of Operations on a device."),
@ApiResponse(code = 500, message = "Error occurred while fetching the operations for the " +
"device.")})
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getDeviceOperations(@ApiParam(name = "type", value = "Define the device type as the value for {type}. " +
"Example: ios, android or windows.",
required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Define the device ID",
required = true) @PathParam("id") String id,
@ApiParam(name = "start", value = "Provide the starting pagination index. Example 10",
required = true) @QueryParam("start") int startIdx,
@ApiParam(name = "length", value = "Provide how many device details you require from" +
" the starting pagination index. For example if " +
"you require the device details from the 10th " +
"pagination index to the 15th, " +
"you must define 10 as the value for start and 5 " +
"as the value for length.",
required = true) @QueryParam("length") int length,
@QueryParam("search") String search);
@GET
@Path("{type}/{id}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting Device Operation Details.",
responseContainer = "List",
notes = "Get the details of operations carried out on a selected device.",
response = org.wso2.carbon.device.mgt.common.operation.mgt.Operation.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "List of Operations on a device."),
@ApiResponse(code = 500, message = "Error occurred while fetching the operations for the " +
"device.")})
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getAllDeviceOperations(@ApiParam(name = "type", value = "Define the device type as the value for {type}. " +
"Example: ios, android or windows.",
required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Define the device ID",
required = true) @PathParam("id") String id);
/* @deprecated */
@POST
@Permission(scope = "operation-modify", permissions = {
"/permission/admin/device-mgt/admin/devices/add"})
Response addOperation(DeviceOperationContext operationContext);
@GET
@Path("{type}/{id}/apps")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting Installed Application Details of a Device.",
responseContainer = "List",
notes = "Get the list of applications that a device has subscribed.",
response = Application.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "List of installed application details of a device.", response = Application.class, responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while fetching the apps of the device" +
".")})
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getInstalledApps(@ApiParam(name = "type", value = "Define the device type as the value for {type}. " +
"Example: ios, android or windows.",
required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Define the device ID",
required = true) @PathParam("id") String id);
@POST
@Path("installApp/{tenantDomain}")
@Permission(scope = "operation-install",
permissions = {"/permission/admin/device-mgt/admin/operations/applications/install-applications"})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "POST",
value = "Installing an Application on a Device.",
notes = "Install a selected application on a device.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Operation was successfully added to the queue."),
@ApiResponse(code = 500, message = "Error occurred while saving the operation.")})
Response installApplication(@ApiParam(name = "applicationWrapper", value = "Details about the application and the" +
" users and roles it should be " +
"installed on.",
required = true) ApplicationWrapper applicationWrapper,
@ApiParam(name = "tenantDomain", value = "Provide the tenant domain as the value for " +
"{tenantDomain}. The default tenant domain " +
"of WSO2 EMM is carbon.super.",
required = true) @PathParam("tenantDomain") String tenantDomain);
@POST
@Path("uninstallApp/{tenantDomain}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "POST",
value = "Uninstalling an Application from a Device.",
notes = "Uninstall a selected application from a device.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Operation was successfully added to the queue."),
@ApiResponse(code = 500, message = "Error occurred while saving the operation.")})
@Permission(scope = "operation-uninstall",
permissions = {"/permission/admin/device-mgt/admin/operations/applications/uninstall-applications"})
Response uninstallApplication(@ApiParam(name = "applicationWrapper", value = "Details about the application and" +
" the users and roles it should be " +
"uninstalled.",
required = true) ApplicationWrapper applicationWrapper,
@ApiParam(name = "tenantDomain", value = "Provide the tenant domain as the value for " +
"{tenantDomain}. The default tenant domain " +
"of WSO2 EMM is carbon.super.",
required = true) @PathParam("tenantDomain") String tenantDomain);
@GET
@Path("activity/{id}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Retrieving the operation details.",
notes = "This will return the operation details including the responses from the devices",
response = Activity.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Activity details provided successfully.."),
@ApiResponse(code = 500, message = "Error occurred while fetching the activity for the supplied id.")})
@Permission(scope = "operation-view", permissions = {"/permission/admin/device-mgt/admin/devices/view"})
Response getActivity(@ApiParam(name = "id", value = "Provide activity id {id} as ACTIVITY_(number)",
required = true) @PathParam("id") String id)
throws MDMAPIException;
@GET
@Path("activity/after/{timestamp}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Retrieving the operation details updated after given timestamp. Timestamp should be given as unix " +
"value in seconds.",
notes = "This will return the operation details including the responses from the devices update after given" +
"time.",
response = Activity.class,
responseContainer = "List")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Activity details provided successfully.."),
@ApiResponse(code = 500, message = "Error occurred while fetching the activity for the supplied id.")})
@Permission(scope = "operation-view", permissions = {"/permission/admin/device-mgt/admin/devices/view"})
Response getActivityUpdatedAfter(@ApiParam(name = "timestamp", value = "Provide the timestamp as unix in seconds.",
required = true) @PathParam("timestamp") String timestamp)
throws MDMAPIException;
}

@ -1,288 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@API(name = "Policy", version = "1.0.0", context = "/devicemgt_admin/policies", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/policies")
@Api(value = "Policy", description = "Policy management related operations can be found here.")
public interface Policy {
@POST
@Path("inactive-policy")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding a Policy.",
notes = "Add a policy using this REST API command. When adding a policy you will have the option of " +
"saving the policy or saving and publishing the policy. Using the REST API command given below " +
"you are able to save a created Policy and this policy will be in the inactive state")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created the policy."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"adding the policy")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response addPolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.",
required = true) PolicyWrapper policyWrapper);
@POST
@Path("active-policy")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding an Active Policy.",
notes = "Add a policy that is in the active state using the REST API command. When adding a policy you " +
"will have the option of saving the policy or saving and publishing the policy. Using the REST " +
"API command given below you are able to save and publish a created policy and this policy will " +
"be in the active state.")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created the policy."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"adding the policy")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response addActivePolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.",
required = true) PolicyWrapper policyWrapper);
@GET
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Policies.",
responseContainer = "List",
notes = "Retrieve the details of all the policies that you have created in WSO2 EMM.",
response = org.wso2.carbon.policy.mgt.common.Policy.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched all policies.",
response = org.wso2.carbon.policy.mgt.common.Policy.class, responseContainer = "List"),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"fetching the policies.")})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getAllPolicies();
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("{id}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of a Policy.",
notes = "Retrieve the details of a selected policy in WSO2 EMM.",
response = org.wso2.carbon.policy.mgt.common.Policy.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched policy details."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"fetching the policies.")})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getPolicy(@ApiParam(name = "id", value = "Policy ID value to identify a policy uniquely.",
required = true) @PathParam("id") int policyId);
@GET
@Path("count")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the Policy Count.",
notes = "Get the number of policies that are created in WSO2 EMM.",
response = int.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched the policy count."),
@ApiResponse(code = 500, message = "Error while Fetching the policy count.")})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getPolicyCount();
@PUT
@Path("{id}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Updating a Policy.",
notes = "If you wish to make changes to an existing policy, you can do so by updating the policy using " +
"this API")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Policy has been updated successfully."),
@ApiResponse(code = 500, message = "Policy Management related exception in policy " +
"update")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"})
Response updatePolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.",
required = true) PolicyWrapper policyWrapper,
@ApiParam(name = "id", value = "Policy ID value to identify a policy uniquely.",
required = true) @PathParam("id") int policyId);
@PUT
@Path("priorities")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Updating the Policy Priority.",
notes = "If you wish to make changes to the existing policy priority order, " +
"you can do so by updating the priority order using this API")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policy Priorities successfully updated."),
@ApiResponse(code = 400, message = "Policy priorities did not update."),
@ApiResponse(code = 500, message = "Error in updating policy priorities.")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"})
Response updatePolicyPriorities(@ApiParam(name = "priorityUpdatedPolicies",
value = "List of policy update details..",
required = true) List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies);
@POST
@Path("bulk-remove")
@Consumes("application/json")
@Produces("application/json")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Removing Multiple Policies.",
notes = "In situations where you need to delete more than one policy you can do so using this API.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully deleted."),
@ApiResponse(code = 400, message = "Policy does not exist."),
@ApiResponse(code = 500, message = "Error in deleting policies.")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/remove"})
Response bulkRemovePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be deleted.",
required = true) List<Integer> policyIds);
@PUT
@Produces("application/json")
@Path("activate")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Activating Policies.",
notes = "Using the REST API command you are able to publish a policy in order to bring a policy that is " +
"in the inactive state to the active state.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully activated."),
@ApiResponse(code = 500, message = "Error in activating policies.")})
@Permission(scope = "policy-modify", permissions = {
"/permission/admin/device-mgt/admin/policies/update",
"/permission/admin/device-mgt/admin/policies/add"})
Response activatePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be activated.",
required = true) List<Integer> policyIds);
@PUT
@Produces("application/json")
@Path("inactivate")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Deactivating Policies.",
notes = "Using the REST API command you are able to unpublish a policy in order to bring a policy that " +
"is in the active state to the inactive state.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully deactivated."),
@ApiResponse(code = 500, message = "Error in deactivating policies.")})
@Permission(scope = "policy-modify", permissions = {
"/permission/admin/device-mgt/admin/policies/update",
"/permission/admin/device-mgt/admin/policies/add"})
Response inactivatePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be deactivated.",
required = true) List<Integer> policyIds) throws MDMAPIException;
@PUT
@Produces("application/json")
@Path("apply-changes")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Applying Changes on Policies.",
notes = "Policies in the active state will be applied to new device that register with WSO2 EMM based on" +
" the policy enforcement criteria . In a situation where you need to make changes to existing" +
" policies (removing, activating, deactivating and updating) or add new policies, the existing" +
" devices will not receive these changes immediately. Once all the required changes are made" +
" you need to apply the changes to push the policy changes to the existing devices.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Changes have been successfully updated."),
@ApiResponse(code = 500, message = "Error in updating policies.")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"})
Response applyChanges();
@GET
@Path("start-task/{milliseconds}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Starting Policy Monitoring.",
notes = "WSO2 EMM monitors the devices to identify any devices that have not complied to an enforced " +
"policy. The policy monitoring task begins at the point WSO2 EMM has a a published policy. " +
"It will monitor the device based on the policy monitoring frequency that you define in " +
"milliseconds.Using this REST API to start the policy monitoring task is optional as " +
"WSO2 EMM uses an OSGI call to start the monitoring task")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policy monitoring service started successfully."),
@ApiResponse(code = 500, message = "Policy Management related exception when starting " +
"monitoring service.")})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response startTaskService(@ApiParam(name = "milliseconds", value = "Policy monitoring frequency in milliseconds.",
required = true) @PathParam("milliseconds") int monitoringFrequency);
@GET
@Path("update-task/{milliseconds}")
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency);
@GET
@Path("stop-task")
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response stopTaskService();
@GET
@Path("{type}/{id}")
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id);
@GET
@Path("{type}/{id}/active-policy")
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Policy Enforced Details of a Device.",
notes = "When a device registers with WSO2 EMM a policy is enforced on the device. Initially the EMM " +
"filters the policies based on the Platform (device type), filters based on the device ownership" +
" type , filters based on the user role or name and finally the policy is enforced on the device.",
response = org.wso2.carbon.policy.mgt.common.Policy.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched current policy."),
@ApiResponse(code = 500, message = "Error occurred while getting the current policy.")})
Response getDeviceActivePolicy(@ApiParam(name = "type", value = "Define the device type as the value for {type}." +
" Example: ios, android, windows..",
required = true) @PathParam("type") String type,
@ApiParam(name = "id", value = "Define the device ID as the value for {id}.",
required = true) @PathParam("id") String id);
//TODO: This API is still not in use, but will be needed when grouping is implemented.
@GET
@Path("/device-group/{user}")
public Response getDeviceGroupsRelatedToPolicies(@PathParam("user") String userName);
}

@ -1,55 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.Api;
import org.wso2.carbon.apimgt.annotations.api.*;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
/**
* These end points provide profile related operations.
*/
@API(name = "Profile", version = "1.0.0", context = "/devicemgt_admin/profiles", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Api(value = "Profile")
@Path("/profiles")
@SuppressWarnings("NonJaxWsWebServices")
public interface Profile {
@POST
@Permission(scope = "profile", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile);
@POST
@Path("{id}")
@Permission(scope = "profile", permissions = {"/permission/admin/device-mgt/admin/policies/update"})
Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile,
@PathParam("id") String profileId);
@DELETE
@Path("{id}")
@Permission(scope = "profile", permissions = {"/permission/admin/device-mgt/admin/policies/remove"})
Response deleteProfile(@PathParam("id") int profileId);
}

@ -1,223 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@API(name = "Role", version = "1.0.0", context = "/devicemgt_admin/roles", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/roles")
@Api(value = "Role", description = "Role management related operations can be found here.")
public interface Role {
@GET
@Produces({ MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the List of Roles.",
responseContainer = "List",
notes = "If you wish to get the details of all the roles in WSO2 EMM, you can do so using this REST API.",
response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of available roles"),
@ApiResponse(code = 500, message = "Error occurred while fetching the role list.") })
@Permission(scope = "roles-view", permissions = {
"/permission/admin/device-mgt/admin/roles/list",
"/permission/admin/device-mgt/admin/users/view",
"/permission/admin/device-mgt/admin/policies/add",
"/permission/admin/device-mgt/admin/policies/update"})
Response getAllRoles();
@GET
@Path("{userStore}")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the List of Roles in a User Store.",
responseContainer = "List",
notes = "If you wish to get the details of all the roles in WSO2 EMM, you can do so using this REST API.",
response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of available roles"),
@ApiResponse(code = 500, message = "Error occurred while fetching the role list.") })
@Permission(scope = "roles-view", permissions = {
"/permission/admin/device-mgt/admin/users/add",
"/permission/admin/device-mgt/admin/roles/list"})
Response getRolesOfUserStore(@ApiParam(name = "userStore", value = "Provide the name of the UserStore you wish to get the" +
" details from ",
required = true) @PathParam("userStore") String userStore);
@GET
@Path("search")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Searching for Roles via the Role Name.",
responseContainer = "List",
notes = "You will have many roles created within WSO2 EMM. As the admin you will need to confirm if a " +
"given role exists in the EMM. In such situation you can search for the role by giving a " +
"character or a few characters of the role name. The search will give you a list of roles that" +
" have the name in the exact order of the characters you provided.",
response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of matching roles"),
@ApiResponse(code = 500, message = "Error occurred while fetching the matching role list" +
".") })
@Permission(scope = "roles-view", permissions = {
"/permission/admin/device-mgt/admin/users/add",
"/permission/admin/device-mgt/admin/roles/list"})
Response getMatchingRoles(@ApiParam(name = "filter", value = "Provide a character or a few characters in the" +
" role name.",
required = true) @QueryParam("filter") String filter);
@GET
@Path("permissions")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Permission Details of a Role.",
notes = "In an organization an individual is associated a with set of responsibilities based on their " +
"role. In WSO2 EMM you are able to configure permissions based on the responsibilities carried " +
"out by a role. Therefore if you wish to retrieve the permission details of a role, you can do " +
"so using this REST API.",
response = UIPermissionNode.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Permission details of a role"),
@ApiResponse(code = 500, message = "Error occurred while fetching the permission " +
"details of a role.") })
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getPermissions(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to get the " +
"permission details.",
required = true) @QueryParam("rolename") String roleName);
@GET
@Path("role")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of a Role.",
notes = "If you wish to get the details of a role in WSO2 EMM, you can do so using this REST API.",
response = RoleWrapper.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Details of a role."),
@ApiResponse(code = 500, message = "Error occurred while retrieving the user role.") })
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getRole(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to get the " +
"details.",
required = true) @QueryParam("rolename") String roleName);
@POST
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding a Role.",
notes = "You are able to add a new role to WSO2 EMM using the REST API.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Added the role."),
@ApiResponse(code = 500, message = "Error occurred while adding the user role.") })
@Permission(scope = "roles-add", permissions = {"/permission/admin/device-mgt/admin/roles/add"})
Response addRole(@ApiParam(name = "roleWrapper", value = "Role and permission details.",
required = true) RoleWrapper roleWrapper);
@PUT
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Updating a Role.",
notes = "There will be situations where you will need to update the role details, such as the permissions" +
" or the role name. In such situation you can update the role details.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Updated the role."),
@ApiResponse(code = 500, message = "Error occurred while updating the user role details" +
".") })
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateRole(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to update.",
required = true) @QueryParam("rolename") String roleName,
@ApiParam(name = "roleWrapper", value = "Role and permission details.",
required = true) RoleWrapper roleWrapper);
@DELETE
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Deleting a Role.",
notes = "In a situation when your Organization identifies that a specific role is no longer required you " +
"will need to remove the role details from WSO2 EMM.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Deleted the role."),
@ApiResponse(code = 500, message = "Error occurred while deleting the user role details" +
".") })
@Permission(scope = "roles-remove", permissions = {"/permission/admin/device-mgt/admin/roles/remove"})
Response deleteRole(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to delete.",
required = true) @QueryParam("rolename") String roleName);
@PUT
@Path("users")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Adding Users to a Role.",
notes = "Defining the users to a role at the point of creating a new role is optional, " +
"therefore you are able to update the users that belong to a given role after you have created " +
"a role using this REST API." +
"Example: Your Organization hires 30 new engineers. Updating the role details for each user can " +
"be cumbersome, therefore you can define all the new employees that belong to the engineering " +
"role using this API.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Added Users to a Role."),
@ApiResponse(code = 500, message = "Error occurred while saving the users of the role.") })
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateUsers(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to update.",
required = true) @QueryParam("rolename") String roleName,
@ApiParam(name = "userList", value = "Provide the names of the users you will to update.",
required = true) List<String> userList);
@GET
@Path("count")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the Role Count.",
response = int.class,
notes = "Get the number of roles in WSO2 EMM.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieved the role count."),
@ApiResponse(code = 500, message = "Error occurred while retrieving the role count.") })
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getRoleCount();
}

@ -1,324 +0,0 @@
/*
* 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.api;
import io.swagger.annotations.*;
import org.apache.axis2.databinding.types.soapencoding.Integer;
import org.wso2.carbon.apimgt.annotations.api.*;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
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.List;
/**
* This represents the JAX-RS services of User related functionality.
*/
@API(name = "User", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"})
// Below Api is for swagger annotations
@Path("/users")
@Api(value = "User", description = "User management related operations can be found here.")
public interface User {
@POST
@Consumes({ MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding a User via the REST API",
notes = "Adds a new user to WSO2 EMM using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 500, message = "Exception in trying to add user by username: 'username'")
})
@Permission(scope = "user-add", permissions = {"/permission/admin/device-mgt/admin/user/add"})
Response addUser(@ApiParam(name = "userWrapper", value = "Includes the required properties to add a user"
+ " as the <JSON_PAYLOAD> value", required = true) UserWrapper userWrapper);
@GET
@Path("view")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of a User",
notes = "If you wish to get the details of a specific user that is registered with WSO2 EMM,"
+ " you can do so using the REST API",
response = UserWrapper.class)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "User information was retrieved successfully"),
@ApiResponse(code = 400, message = "User by username: 'username' does not exist"),
@ApiResponse(code = 500, message = "Exception in trying to retrieve user by username: 'username'")
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"})
Response getUser(@ApiParam(name = "username", value = "Provide the name of the user you wish to get the"
+ " details of as the value", required = true)
@QueryParam("username") String username);
@PUT
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "PUT",
value = "Updating Details of a User",
notes = "There will be situations where you will want to update the user details. In such "
+ "situation you can update the user details using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "User by username: 'username' was successfully updated"),
@ApiResponse(code = 409, message = "User by username: 'username' doesn't exists. Therefore, "
+ "request made to update user was refused"),
@ApiResponse(code = 500, message = "Exception in trying to update user by username: 'username'")
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/update"})
Response updateUser(@ApiParam(name = "userWrapper", value = "Provide the name of the user you wish to get"
+ " the details of as the value", required = true) UserWrapper userWrapper,
@ApiParam(name = "username", value = "Provide the name of the user you wish to get "
+ "the details of as the value", required = true)
@QueryParam("username") String username);
@DELETE
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Deleting a User",
notes = "In a situation where an employee leaves the organization you will need to remove the"
+ " user details from WSO2 EMM. In such situations you can use this REST API "
+ "to remove a user")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "User by username: 'username' was successfully removed"),
@ApiResponse(code = 400, message = "User by username: 'username' does not exist for removal"),
@ApiResponse(code = 500, message = "Exception in trying to remove user by username: 'username'")
})
@Permission(scope = "user-remove", permissions = {"/permission/admin/device-mgt/admin/user/remove"})
Response removeUser(@ApiParam(name = "username", value = "Provide the name of the user you wish to delete"
+ " as the value for {username}", required = true)
@QueryParam("username") String username);
@GET
@Path("roles")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the Role Details of a User",
notes = "A user can be assigned to one or more role in WSO2 EMM. Using this REST API you are "
+ "able to get the role/roles a user is assigned to",
response = String.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "User roles obtained for user : 'username'"),
@ApiResponse(code = 400, message = "User by username: 'username' does not exist for role retrieval"),
@ApiResponse(code = 500, message = "Exception in trying to retrieve roles for user by username: 'username'")
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"})
Response getRolesOfUser(@ApiParam(name = "username", value = "Provide the user name of the user you wish to get"
+ " the role details", required = true) @QueryParam("username") String username);
@GET
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Users",
notes = "If you wish to get the details of all the user registered with WSO2 EMM, you can do so "
+ "using the REST API",
response = UserWrapper.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "All users were successfully retrieved"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of users")
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getAllUsers();
@GET
@Path("{filter}")
@Produces({MediaType.APPLICATION_JSON})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getMatchingUsers(@PathParam("filter") String filter);
@GET
@Path("view-users")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting User Details by Searching via the User Name",
notes = "You will have 100+ users registered with WSO2 EMM. If you wish to retrieve the user "
+ "details of a specific user, and you only remember part of the user's username, "
+ "you are able to retrieve the user details by giving a character or a few characters "
+ "in the username",
response = String.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "All users by username were successfully retrieved. Obtained"
+ " user count: 'count'"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of users")
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getAllUsersByUsername(@ApiParam(name = "username", value = "Provide any user detail of the user"
+ " as the value for {username} to retrieve the user details, such "
+ "as email address, first name or last name", required = true)
@QueryParam("username") String userName);
@GET
@Path("users-by-username")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Searching for a User Name",
notes = "You will have 100+ users registered with WSO2 EMM. Therefore if you are unsure of the "
+ "user name of a user and need to retrieve the details of a specific user, you can "
+ "search for that user by giving a character or a few characters in the username. "
+ "You will be given a list of users having the user name with the exact order of the "
+ "characters you provided",
response = String.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "All users by username were successfully retrieved. Obtained"
+ " user count: 'count'"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of users")
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getAllUserNamesByUsername(@ApiParam(name = "username", value = "Provide a character or a few "
+ "character in the user name as the value for {username}",
required = true) @QueryParam("username") String userName);
@POST
@Path("email-invitation")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Sending Enrollment Invitations to Users",
notes = "Send the users a mail inviting them to download the EMM mobile application on their "
+ "devices using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Email invitation was successfully sent to user"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of users")
})
@Permission(scope = "user-invite", permissions = {"/permission/admin/device-mgt/admin/users/invite"})
Response inviteExistingUsersToEnrollDevice(@ApiParam(name = "usernames", value = "List of the users to be"
+ " invited as the <JSON_PAYLOAD>", required = true)
List<String> usernames);
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("devices")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Device Details of a User",
notes = "If you wish to get the details of the devices enrolled by a specific user, you can do "
+ "so using this REST API",
response = org.wso2.carbon.device.mgt.common.Device.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 500, message = "Device management error")
})
@Permission(scope = "user-view", permissions = {
"/permission/admin/device-mgt/user/devices/list",
"/permission/admin/device-mgt/admin/devices/list"})
Response getAllDeviceOfUser(@ApiParam(name = "username", value = "Provide the name of the user you wish "
+ "to get the details", required = true) @QueryParam("username")
String username,
@ApiParam(name = "start", value = "Provide the starting pagination index",
required = true) @QueryParam("start") int startIdx,
@ApiParam(name = "length", value = "Provide how many device details you "
+ "require from the starting pagination index", required = true)
@QueryParam("length") int length);
@GET
@Path("count")
@ApiOperation(
httpMethod = "GET",
value = "Getting the User Count",
notes = "Get the number of users in WSO2 EMM",
response = int.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of users that exist"
+ " within the current tenant")
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getUserCount();
@PUT
@Path("{roleName}/users")
@Produces({MediaType.APPLICATION_JSON})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/update"})
Response updateRoles(@PathParam("roleName") String roleName, List<String> userList);
@POST
@Path("change-password")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Changing the User Password",
notes = "A user is able to change the password to secure their EMM profile via this REST API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "UserImpl password by username: 'Username' was "
+ "successfully changed"),
@ApiResponse(code = 400, message = "Old password does not match"),
@ApiResponse(code = 400, message = "Could not change the password of the user: 'Username'. The"
+ " Character Encoding is not supported"),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "user-password-modify", permissions = {"/permission/admin/login"})
Response resetPassword(@ApiParam(name = "credentials", value = "Include the required properties to change"
+ " the user password as <JSON_PAYLOAD> value", required = true)
UserCredentialWrapper credentials);
@POST
@Path("reset-password")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Resetting the User Password",
notes = "In a situation where you need to block a user from accessing their EMM profile, "
+ "the EMM administrator is able to reset the password. This will change the user's "
+ "password and the user will not be able to able to login to the account as he/she is "
+ "not aware of the new password.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "UserImpl password by username: 'Username' was "
+ "successfully changed"),
@ApiResponse(code = 400, message = "Old password does not match"),
@ApiResponse(code = 400, message = "Could not change the password of the user: 'Username'. The"
+ " Character Encoding is not supported"),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@Permission(scope = "user-password-reset", permissions = {"/permission/admin/device-mgt/admin/users/password-reset"})
Response resetPasswordByAdmin(@ApiParam(name = "credentials", value = "Include the required properties "
+ "to change a user password as <JSON_PAYLOAD> value",
required = true) UserCredentialWrapper credentials);
}

@ -1,59 +0,0 @@
/*
* 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.api.common;
/**
* Custom exception class for handling CDM API related exceptions.
*/
public class MDMAPIException extends Exception {
private static final long serialVersionUID = 7950151650447893900L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public MDMAPIException(String msg, Exception e) {
super(msg, e);
setErrorMessage(msg);
}
public MDMAPIException(String msg, Throwable cause) {
super(msg, cause);
setErrorMessage(msg);
}
public MDMAPIException(String msg) {
super(msg);
setErrorMessage(msg);
}
public MDMAPIException() {
super();
}
public MDMAPIException(Throwable cause) {
super(cause);
}
}

@ -1,214 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.jaxrs.api.Certificate;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
import org.wso2.carbon.device.mgt.jaxrs.exception.BadRequestException;
import org.wso2.carbon.device.mgt.jaxrs.exception.Message;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* All the certificate related tasks such as saving certificates, can be done through this endpoint.
*/
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"})
@Consumes({ "application/json", "application/xml" })
public class CertificateImpl implements Certificate {
private static Log log = LogFactory.getLog(OperationImpl.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();
}
}
}

@ -1,113 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.jaxrs.api.Configuration;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* General Tenant Configuration REST-API implementation.
* All end points support JSON, XMl with content negotiation.
*/
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"})
@Consumes({ "application/json", "application/xml" })
public class ConfigurationImpl implements Configuration{
private static Log log = LogFactory.getLog(ConfigurationImpl.class);
@POST
public Response saveTenantConfiguration(PlatformConfiguration configuration) {
ResponsePayload responseMsg = new ResponsePayload();
try {
DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
//Schedule the task service
DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
responseMsg.setMessageFromServer("Tenant configuration saved successfully.");
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (ConfigurationManagementException e) {
String msg = "Error occurred while saving the tenant configuration.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
public Response getConfiguration() {
String msg;
try {
PlatformConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService().
getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
ConfigurationEntry configurationEntry = new ConfigurationEntry();
configurationEntry.setContentType("text");
configurationEntry.setName("notifierFrequency");
configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency());
List<ConfigurationEntry> configList = tenantConfiguration.getConfiguration();
if (configList == null) {
configList = new ArrayList<>();
}
configList.add(configurationEntry);
tenantConfiguration.setConfiguration(configList);
return Response.status(Response.Status.OK).entity(tenantConfiguration).build();
} catch (ConfigurationManagementException e) {
msg = "Error occurred while retrieving the tenant configuration.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
public Response updateConfiguration(PlatformConfiguration configuration) {
ResponsePayload responseMsg = new ResponsePayload();
try {
DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
//Schedule the task service
DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
responseMsg.setMessageFromServer("Tenant configuration updated successfully.");
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (ConfigurationManagementException e) {
String msg = "Error occurred while updating the tenant configuration.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -1,687 +0,0 @@
/*
* 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.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet;
import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup;
import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails;
import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet;
import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.beans.DashboardGadgetDataWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.DashboardPaginationGadgetDataWrapper;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* This class consists of dashboard related REST APIs
* to be consumed by individual client gadgets such as
* [1] Overview of Devices,
* [2] Potential Vulnerabilities,
* [3] Non-compliant Devices by Features,
* [4] Device Groupings and etc.
*/
@Consumes({"application/json"})
@Produces({"application/json"})
@SuppressWarnings("NonJaxWsWebServices")
public class DashboardImpl implements Dashboard{
private static Log log = LogFactory.getLog(DashboardImpl.class);
private static final String FLAG_TRUE = "true";
private static final String FLAG_FALSE = "false";
// Constants related to common error-response messages
private static final String INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY = "Received an invalid value for " +
"query parameter : " + POTENTIAL_VULNERABILITY + ", Should be either NON_COMPLIANT or UNMONITORED.";
private static final String INVALID_QUERY_PARAM_VALUE_START_INDEX = "Received an invalid value for " +
"query parameter : " + START_INDEX + ", Should not be lesser than 0.";
private static final String INVALID_QUERY_PARAM_VALUE_RESULT_COUNT = "Received an invalid value for " +
"query parameter : " + RESULT_COUNT + ", Should not be lesser than 5.";
private static final String INVALID_QUERY_PARAM_VALUE_PAGINATION_ENABLED = "Received an invalid value for " +
"query parameter : " + PAGINATION_ENABLED + ", Should be either true or false.";
private static final String REQUIRED_QUERY_PARAM_VALUE_NON_COMPLIANT_FEATURE_CODE = "Missing required query " +
"parameter : " + NON_COMPLIANT_FEATURE_CODE;
private static final String REQUIRED_QUERY_PARAM_VALUE_PAGINATION_ENABLED = "Missing required query " +
"parameter : " + PAGINATION_ENABLED;
private static final String ERROR_IN_RETRIEVING_REQUESTED_DATA = "Error in retrieving requested data.";
@GET
@Path("device-count-overview")
public Response getOverviewDeviceCounts() {
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
// getting total device count
DeviceCountByGroup totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve total device count.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
List<DeviceCountByGroup> totalDeviceCountInListEntry = new ArrayList<>();
totalDeviceCountInListEntry.add(totalDeviceCount);
dashboardGadgetDataWrapper1.setContext("Total-device-count");
dashboardGadgetDataWrapper1.setGroupingAttribute(null);
dashboardGadgetDataWrapper1.setData(totalDeviceCountInListEntry);
// getting device counts by connectivity statuses
List<DeviceCountByGroup> deviceCountsByConnectivityStatuses;
try {
deviceCountsByConnectivityStatuses = gadgetDataService.getDeviceCountsByConnectivityStatuses();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve device counts by connectivity statuses.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("Device-counts-by-connectivity-statuses");
dashboardGadgetDataWrapper2.setGroupingAttribute(CONNECTIVITY_STATUS);
dashboardGadgetDataWrapper2.setData(deviceCountsByConnectivityStatuses);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("device-counts-by-potential-vulnerabilities")
public Response getDeviceCountsByPotentialVulnerabilities() {
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
List<DeviceCountByGroup> deviceCountsByPotentialVulnerabilities;
try {
deviceCountsByPotentialVulnerabilities = gadgetDataService.getDeviceCountsByPotentialVulnerabilities();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve device counts by potential vulnerabilities.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Device-counts-by-potential-vulnerabilities");
dashboardGadgetDataWrapper.setGroupingAttribute(POTENTIAL_VULNERABILITY);
dashboardGadgetDataWrapper.setData(deviceCountsByPotentialVulnerabilities);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("non-compliant-device-counts-by-features")
public Response getNonCompliantDeviceCountsByFeatures(@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount) {
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getNonCompliantDeviceCountsByFeatures(startIndex, resultCount);
} catch (InvalidStartIndexValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a non-compliant set " +
"of device counts by features.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(INVALID_QUERY_PARAM_VALUE_START_INDEX).build();
} catch (InvalidResultCountValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a non-compliant set " +
"of device counts by features.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(INVALID_QUERY_PARAM_VALUE_RESULT_COUNT).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a non-compliant set of device counts by features.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
dashboardPaginationGadgetDataWrapper.setContext("Non-compliant-device-counts-by-features");
dashboardPaginationGadgetDataWrapper.setGroupingAttribute(NON_COMPLIANT_FEATURE_CODE);
dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("device-counts-by-groups")
public Response getDeviceCountsByGroups(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
ExtendedFilterSet filterSet = new ExtendedFilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating device-Counts-by-platforms Data Wrapper
List<DeviceCountByGroup> deviceCountsByPlatforms;
try {
deviceCountsByPlatforms = gadgetDataService.getDeviceCountsByPlatforms(filterSet);
} catch (InvalidPotentialVulnerabilityValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of device counts by platforms.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by platforms.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper1.setContext("Device-counts-by-platforms");
dashboardGadgetDataWrapper1.setGroupingAttribute(PLATFORM);
dashboardGadgetDataWrapper1.setData(deviceCountsByPlatforms);
// creating device-Counts-by-ownership-types Data Wrapper
List<DeviceCountByGroup> deviceCountsByOwnerships;
try {
deviceCountsByOwnerships = gadgetDataService.getDeviceCountsByOwnershipTypes(filterSet);
} catch (InvalidPotentialVulnerabilityValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of device counts by ownerships.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by ownerships.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("Device-counts-by-ownerships");
dashboardGadgetDataWrapper2.setGroupingAttribute(OWNERSHIP);
dashboardGadgetDataWrapper2.setData(deviceCountsByOwnerships);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("feature-non-compliant-device-counts-by-groups")
public Response getFeatureNonCompliantDeviceCountsByGroups(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
BasicFilterSet filterSet = new BasicFilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating feature-non-compliant-device-Counts-by-platforms Data Wrapper
List<DeviceCountByGroup> featureNonCompliantDeviceCountsByPlatforms;
try {
featureNonCompliantDeviceCountsByPlatforms = gadgetDataService.
getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filterSet);
} catch (InvalidFeatureCodeValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of feature " +
"non-compliant device counts by platforms.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_NON_COMPLIANT_FEATURE_CODE).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
"device counts by platforms.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper1.setContext("Feature-non-compliant-device-counts-by-platforms");
dashboardGadgetDataWrapper1.setGroupingAttribute(PLATFORM);
dashboardGadgetDataWrapper1.setData(featureNonCompliantDeviceCountsByPlatforms);
// creating feature-non-compliant-device-Counts-by-ownership-types Data Wrapper
List<DeviceCountByGroup> featureNonCompliantDeviceCountsByOwnerships;
try {
featureNonCompliantDeviceCountsByOwnerships = gadgetDataService.
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filterSet);
} catch (InvalidFeatureCodeValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature " +
"non-compliant device counts by ownerships.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_NON_COMPLIANT_FEATURE_CODE).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
"device counts by ownerships.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("Feature-non-compliant-device-counts-by-ownerships");
dashboardGadgetDataWrapper2.setGroupingAttribute(OWNERSHIP);
dashboardGadgetDataWrapper2.setData(featureNonCompliantDeviceCountsByOwnerships);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("filtered-device-count-over-total")
public Response getFilteredDeviceCountOverTotal(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
ExtendedFilterSet filterSet = new ExtendedFilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating filteredDeviceCount Data Wrapper
DeviceCountByGroup filteredDeviceCount;
try {
filteredDeviceCount = gadgetDataService.getDeviceCount(filterSet);
} catch (InvalidPotentialVulnerabilityValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered device count over the total.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered device count over the total.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
// creating TotalDeviceCount Data Wrapper
DeviceCountByGroup totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve the total device count over filtered.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
List<Object> filteredDeviceCountOverTotalDataWrapper = new ArrayList<>();
filteredDeviceCountOverTotalDataWrapper.add(filteredDeviceCount);
filteredDeviceCountOverTotalDataWrapper.add(totalDeviceCount);
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Filtered-device-count-over-total");
dashboardGadgetDataWrapper.setGroupingAttribute(null);
dashboardGadgetDataWrapper.setData(filteredDeviceCountOverTotalDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("feature-non-compliant-device-count-over-total")
public Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
BasicFilterSet filterSet = new BasicFilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating featureNonCompliantDeviceCount Data Wrapper
DeviceCountByGroup featureNonCompliantDeviceCount;
try {
featureNonCompliantDeviceCount = gadgetDataService.
getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filterSet);
} catch (InvalidFeatureCodeValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a feature non-compliant device count over the total.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_NON_COMPLIANT_FEATURE_CODE).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a feature non-compliant device count over the total.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
// creating TotalDeviceCount Data Wrapper
DeviceCountByGroup totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve the total device count over filtered feature non-compliant.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
List<Object> featureNonCompliantDeviceCountOverTotalDataWrapper = new ArrayList<>();
featureNonCompliantDeviceCountOverTotalDataWrapper.add(featureNonCompliantDeviceCount);
featureNonCompliantDeviceCountOverTotalDataWrapper.add(totalDeviceCount);
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Feature-non-compliant-device-count-over-total");
dashboardGadgetDataWrapper.setGroupingAttribute(null);
dashboardGadgetDataWrapper.setData(featureNonCompliantDeviceCountOverTotalDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("devices-with-details")
public Response getDevicesWithDetails(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership,
@QueryParam(PAGINATION_ENABLED) String paginationEnabled,
@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount) {
if (paginationEnabled == null) {
log.error("Bad request on retrieving a filtered set of devices with details @ " +
"Dashboard API layer. " + REQUIRED_QUERY_PARAM_VALUE_PAGINATION_ENABLED);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_PAGINATION_ENABLED).build();
} else if (FLAG_TRUE.equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
ExtendedFilterSet filterSet = new ExtendedFilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getDevicesWithDetails(filterSet, startIndex, resultCount);
} catch (InvalidPotentialVulnerabilityValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
} catch (InvalidStartIndexValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_START_INDEX).build();
} catch (InvalidResultCountValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_RESULT_COUNT).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of devices with details.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
dashboardPaginationGadgetDataWrapper.setContext("Filtered-and-paginated-devices-with-details");
dashboardPaginationGadgetDataWrapper.setGroupingAttribute(null);
dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else if (FLAG_FALSE.equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
ExtendedFilterSet filterSet = new ExtendedFilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
List<DeviceWithDetails> devicesWithDetails;
try {
devicesWithDetails = gadgetDataService.getDevicesWithDetails(filterSet);
} catch (InvalidPotentialVulnerabilityValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_POTENTIAL_VULNERABILITY).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of devices with details.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Filtered-devices-with-details");
dashboardGadgetDataWrapper.setGroupingAttribute(null);
dashboardGadgetDataWrapper.setData(devicesWithDetails);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
log.error("Bad request on retrieving a filtered set of devices with details @ " +
"Dashboard API layer. " + INVALID_QUERY_PARAM_VALUE_PAGINATION_ENABLED);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_PAGINATION_ENABLED).build();
}
}
@GET
@Path("feature-non-compliant-devices-with-details")
public Response getFeatureNonCompliantDevicesWithDetails(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP) String ownership,
@QueryParam(PAGINATION_ENABLED) String paginationEnabled,
@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount) {
if (paginationEnabled == null) {
log.error("Bad request on retrieving a filtered set of feature non-compliant devices with " +
"details @ Dashboard API layer. " + REQUIRED_QUERY_PARAM_VALUE_PAGINATION_ENABLED);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_PAGINATION_ENABLED).build();
} else if (FLAG_TRUE.equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
BasicFilterSet filterSet = new BasicFilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode,
filterSet, startIndex, resultCount);
} catch (InvalidFeatureCodeValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_NON_COMPLIANT_FEATURE_CODE).build();
} catch (InvalidStartIndexValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_START_INDEX).build();
} catch (InvalidResultCountValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_RESULT_COUNT).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature " +
"non-compliant devices with details.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
dashboardPaginationGadgetDataWrapper.
setContext("Filtered-and-paginated-feature-non-compliant-devices-with-details");
dashboardPaginationGadgetDataWrapper.setGroupingAttribute(null);
dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else if (FLAG_FALSE.equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = DeviceMgtAPIUtils.getGadgetDataService();
// constructing filter set
BasicFilterSet filterSet = new BasicFilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
List<DeviceWithDetails> featureNonCompliantDevicesWithDetails;
try {
featureNonCompliantDevicesWithDetails = gadgetDataService.
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet);
} catch (InvalidFeatureCodeValueException e) {
log.error("Bad request and error occurred @ Gadget Data Service layer due to " +
"invalid (query) parameter value. This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant devices with details.", e);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(REQUIRED_QUERY_PARAM_VALUE_NON_COMPLIANT_FEATURE_CODE).build();
} catch (DataAccessLayerException e) {
log.error("An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature " +
"non-compliant devices with details.", e);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).
entity(ERROR_IN_RETRIEVING_REQUESTED_DATA).build();
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Filtered-feature-non-compliant-devices-with-details");
dashboardGadgetDataWrapper.setGroupingAttribute(null);
dashboardGadgetDataWrapper.setData(featureNonCompliantDevicesWithDetails);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
log.error("Bad request on retrieving a filtered set of feature non-compliant devices with " +
"details @ Dashboard API layer. " + INVALID_QUERY_PARAM_VALUE_PAGINATION_ENABLED);
return Response.status(HttpStatus.SC_BAD_REQUEST).
entity(INVALID_QUERY_PARAM_VALUE_PAGINATION_ENABLED).build();
}
}
}

@ -1,285 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.Device;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Device related operations
*/
@SuppressWarnings("NonJaxWsWebServices")
public class DeviceImpl implements Device{
private static Log log = LogFactory.getLog(DeviceImpl.class);
/**
* Get all devices. We have to use accept all the necessary query parameters sent by datatable.
* Hence had to put lot of query params here.
*
* @return Device List
*/
@GET
public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user,
@QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status,
@QueryParam("start") int startIdx, @QueryParam("length") int length,
@QueryParam("device-name") String deviceName,
@QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) {
try {
DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService();
//Length > 0 means this is a pagination request.
if (length > 0) {
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
paginationRequest.setDeviceName(deviceName);
paginationRequest.setOwner(user);
if (ownership != null) {
paginationRequest.setOwnership(ownership.toString());
}
if (status != null) {
paginationRequest.setStatus(status.toString());
}
paginationRequest.setDeviceType(type);
return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build();
}
List<org.wso2.carbon.device.mgt.common.Device> allDevices;
if ((type != null) && !type.isEmpty()) {
allDevices = service.getAllDevices(type);
} else if ((user != null) && !user.isEmpty()) {
allDevices = service.getDevicesOfUser(user);
} else if ((role != null) && !role.isEmpty()) {
allDevices = service.getAllDevicesOfRole(role);
} else if (status != null) {
allDevices = service.getDevicesByStatus(status);
} else if (deviceName != null) {
allDevices = service.getDevicesByName(deviceName);
} else {
allDevices = service.getAllDevices();
}
return Response.status(Response.Status.OK).entity(allDevices).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the device list.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Fetch device details for a given device type and device Id.
*
* @return Device wrapped inside Response
*/
@GET
@Path("view")
@Produces({MediaType.APPLICATION_JSON})
public Response getDevice(@QueryParam("type") String type,
@QueryParam("id") String id) {
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
org.wso2.carbon.device.mgt.common.Device device;
try {
device = deviceManagementProviderService.getDevice(deviceIdentifier);
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the device information.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
if (device == null) {
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
responsePayload.setMessageFromServer("Requested device by type: " +
type + " and id: " + id + " does not exist.");
return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build();
} else {
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + ".");
responsePayload.setResponseContent(device);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
}
/**
* Fetch device details of a given user.
*
* @param user User Name
* @return Device
*/
@GET
@Path("user/{user}")
public Response getDeviceOfUser(@PathParam("user") String user) {
List<org.wso2.carbon.device.mgt.common.Device> devices;
try {
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user);
if (devices == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.status(Response.Status.OK).entity(devices).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the devices list of given user.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Fetch device count of a given user.
*
* @param user User Name
* @return Device
*/
@GET
@Path("user/{user}/count")
public Response getDeviceCountOfUser(@PathParam("user") String user) {
try {
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user);
return Response.status(Response.Status.OK).entity(count).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the devices list of given user.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Get current device count
*
* @return device count
*/
@GET
@Path("count")
public Response getDeviceCount() {
try {
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount();
return Response.status(Response.Status.OK).entity(count).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the device count.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Get the list of devices that matches with the given name.
*
* @param deviceName Device name
* @param tenantDomain Callee tenant domain
* @return list of devices.
*/
@GET
@Path("name/{name}/{tenantDomain}")
public Response getDevicesByName(@PathParam("name") String deviceName,
@PathParam("tenantDomain") String tenantDomain) {
List<org.wso2.carbon.device.mgt.common.Device> devices;
try {
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName);
return Response.status(Response.Status.OK).entity(devices).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the devices list of device name.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Get the list of available device types.
*
* @return list of device types.
*/
@GET
@Path("types")
public Response getDeviceTypes() {
List<DeviceType> deviceTypes;
try {
deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes();
return Response.status(Response.Status.OK).entity(deviceTypes).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Update device.
*
* @return update status.
*/
@PUT
@Path("type/{type}/id/{deviceId}")
public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId,
org.wso2.carbon.device.mgt.common.Device updatedDevice) {
try {
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(deviceType);
deviceIdentifier.setId(deviceId);
org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier);
device.setName(updatedDevice.getName());
device.setDescription(updatedDevice.getDescription());
Boolean response = deviceManagementService.modifyEnrollment(device);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* disenroll device.
*
* @return disenrollment status.
*/
@DELETE
@Path("type/{type}/id/{deviceId}")
public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) {
try {
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(deviceType);
deviceIdentifier.setId(deviceId);
Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -1,140 +0,0 @@
/*
* 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.api.impl;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.jaxrs.api.DeviceInformation;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class DeviceInformationImpl implements DeviceInformation {
private static Log log = LogFactory.getLog(DeviceInformationImpl.class);
@GET
@Path("{type}/{id}")
public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) {
DeviceInformationManager informationManager;
DeviceInfo deviceInfo;
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id);
deviceIdentifier.setType(type);
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceInfo = informationManager.getDeviceInfo(deviceIdentifier);
} 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("list")
public Response getDevicesInfo(List<DeviceIdentifier> deviceIdentifiers) {
DeviceInformationManager informationManager;
List<DeviceInfo> deviceInfos;
try {
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceInfos = informationManager.getDevicesInfo(deviceIdentifiers);
} 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(deviceInfos).build();
}
@GET
@Path("location/{type}/{id}")
public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) {
DeviceInformationManager informationManager;
DeviceLocation deviceLocation;
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id);
deviceIdentifier.setType(type);
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
} catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device location.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(deviceLocation).build();
}
@Override
@Path("location/list")
public Response getDeviceLocations(@ApiParam(name = "deviceIdentifiers", value = "List of device identifiers",
required = true) List<DeviceIdentifier> deviceIdentifiers) {
DeviceInformationManager informationManager;
List<DeviceLocation> deviceLocations;
try {
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceLocations = informationManager.getDeviceLocations(deviceIdentifiers);
} catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device location.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(deviceLocations).build();
}
@Override
@Path("application/{type}/{id}")
public Response getDeviceApplications(@PathParam("type") String type, @PathParam("id") String id) {
List<Application> applications;
ApplicationManagementProviderService applicationManagementProviderService;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
try {
deviceIdentifier.setType(type);
deviceIdentifier.setId(id);
applicationManagementProviderService = DeviceMgtAPIUtils.getAppManagementService();
applications = applicationManagementProviderService.getApplicationListForDevice(deviceIdentifier);
} catch (ApplicationManagementException e) {
String msg = "Error occurred while fetching the apps of the device.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(applications).build();
}
}

@ -1,110 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.DeviceNotification;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* DeviceNotification management REST-API implementation.
* All end points support JSON, XMl with content negotiation.
*/
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"})
@Consumes({ "application/json", "application/xml" })
public class DeviceNotificationImpl implements DeviceNotification{
private static Log log = LogFactory.getLog(ConfigurationImpl.class);
@GET
public Response getNotifications() {
String msg;
try {
List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications();
return Response.status(Response.Status.OK).entity(notifications).build();
} catch (NotificationManagementException e) {
msg = "Error occurred while retrieving the notification list.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("{status}")
public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) {
String msg;
try {
List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status);
return Response.status(Response.Status.OK).entity(notifications).build();
} catch (NotificationManagementException e) {
msg = "Error occurred while retrieving the notification list.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
@Path("{id}/{status}")
public Response updateNotificationStatus(@PathParam("id") int id,
@PathParam("status") Notification.Status status) {
ResponsePayload responseMsg = new ResponsePayload();
try {
DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status);
responseMsg.setMessageFromServer("Notification status updated successfully.");
responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED);
return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build();
} catch (NotificationManagementException e) {
String msg = "Error occurred while updating notification status.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@POST
public Response addNotification(Notification notification) {
ResponsePayload responseMsg = new ResponsePayload();
try {
DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification);
responseMsg.setMessageFromServer("Notification has been added successfully.");
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (NotificationManagementException e) {
String msg = "Error occurred while updating notification status.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -1,83 +0,0 @@
/*
* 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.api.impl;
import io.swagger.annotations.Api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.jaxrs.api.DeviceSearch;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.util.List;
@Path("/search")
@Api(value = "DeviceSearch", description = "Device searching related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
public class DeviceSearchImpl implements DeviceSearch {
private static Log log = LogFactory.getLog(DeviceSearchImpl.class);
@GET
public Response getDeviceInfo(SearchContext searchContext) {
SearchManagerService searchManagerService;
List<DeviceWrapper> devices;
try {
searchManagerService = DeviceMgtAPIUtils.getSearchManagerService();
devices = searchManagerService.search(searchContext);
} catch (SearchMgtException e) {
String msg = "Error occurred while searching 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(devices).build();
}
@POST
@Path("after/{time}")
public Response getUpdatedDevices(@PathParam("time") String time){
SearchManagerService searchManagerService;
List<DeviceWrapper> devices;
try {
searchManagerService = DeviceMgtAPIUtils.getSearchManagerService();
devices = searchManagerService.getUpdated(Long.parseLong(time));
} catch (SearchMgtException e) {
String msg = "Error occurred while retrieving the updated device information after the given time.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(devices).build();
}
}

@ -1,66 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.Feature;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Features
*/
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"})
public class FeatureImpl implements Feature{
private static Log log = LogFactory.getLog(FeatureImpl.class);
/**
* Get all features for Mobile Device Type
*
* @return Feature
*/
@GET
@Path("/{type}")
public Response getFeatures(@PathParam("type") String type) {
List<org.wso2.carbon.device.mgt.common.Feature> features;
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
features = dmService.getFeatureManager(type).getFeatures();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving the list of features";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(features).build();
}
}

@ -1,521 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.api.Group;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class GroupImpl implements Group {
private static final String GROUP_CANNOT_NULL_MSG = "Group cannot be null.";
private static final String GROUP_NAME_INVALID_MSG = "Provided group name is invalid. Should be in minimum 3 " +
"characters long and should not include any whitespaces.";
private static Log log = LogFactory.getLog(GroupImpl.class);
@Override
@POST
@Consumes("application/json")
public Response createGroup(DeviceGroup group) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (group == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(GROUP_CANNOT_NULL_MSG).build();
} else if (group.getName() == null || !group.getName().matches("^[\\S]{3,30}$")) {
return Response.status(Response.Status.BAD_REQUEST).entity(GROUP_NAME_INVALID_MSG).build();
}
group.setOwner(owner);
group.setDateOfCreation(new Date().getTime());
group.setDateOfLastUpdate(new Date().getTime());
try {
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner,
DeviceGroupConstants.Roles.DEFAULT_OPERATOR_ROLE,
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_STATS_MONITOR_ROLE,
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_POLICIES,
DeviceGroupConstants.Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_MANAGE_POLICIES,
DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS,
DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS);
return Response.status(Response.Status.CREATED).build();
} catch (GroupAlreadyExistException e) {
return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/owner/{owner}/name/{groupName}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
DeviceGroup group) {
if (group.getName() == null || !group.getName().matches("^[\\S]{3,30}$")) {
return Response.status(Response.Status.BAD_REQUEST).entity(GROUP_NAME_INVALID_MSG).build();
}
try {
DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(group, groupName, owner);
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/owner/{owner}/name/{groupName}")
@DELETE
public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try {
DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner);
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
log.error(e.getMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@GET
@Produces("application/json")
public Response getGroups(@QueryParam("start") int startIndex, @QueryParam("length") int length) {
try {
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
.getGroups(startIndex, length);
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/all")
@GET
@Produces("application/json")
public Response getAllGroups() {
try {
GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils
.getGroupManagementProviderService();
PaginationResult paginationResult = groupManagementProviderService
.getGroups(0, groupManagementProviderService.getGroupCount());
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult.getData()).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/user/{user}")
@GET
@Produces("application/json")
public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex,
@QueryParam("length") int length) {
try {
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
.getGroups(userName, startIndex, length);
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/owner/{owner}/name/{groupName}")
@GET
@Produces("application/json")
public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try {
DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner);
if (deviceGroup != null) {
return Response.status(Response.Status.OK).entity(deviceGroup).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/user/{user}/search")
@GET
@Produces("application/json")
public Response findGroups(@QueryParam("groupName") String groupName, @PathParam("user") String user) {
try {
List<DeviceGroup> groups = DeviceMgtAPIUtils.getGroupManagementProviderService()
.findInGroups(groupName, user);
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
groups.toArray(deviceGroups);
return Response.status(Response.Status.OK).entity(deviceGroups).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/user/{user}/all")
@GET
@Produces("application/json")
public Response getGroups(@PathParam("user") String userName, @QueryParam("permission") String permission) {
try {
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
List<DeviceGroup> groups;
if (permission != null) {
groups = groupManagementService.getGroups(userName, permission);
} else {
groups = groupManagementService.getGroups(userName);
}
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
groups.toArray(deviceGroups);
return Response.status(Response.Status.OK).entity(deviceGroups).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/count")
@GET
@Produces("application/json")
public Response getAllGroupCount() {
try {
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount();
return Response.status(Response.Status.OK).entity(count).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/user/{user}/count")
@GET
@Produces("application/json")
public Response getGroupCount(@PathParam("user") String userName) {
try {
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName);
return Response.status(Response.Status.OK).entity(count).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/owner/{owner}/name/{groupName}/share")
@PUT
@Produces("application/json")
public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@FormParam("shareUser") String shareUser,
@FormParam("roleName") String sharingRole) {
try {
boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup(
shareUser, groupName, owner, sharingRole);
if (isShared) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
}
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/owner/{owner}/name/{groupName}/unshare")
@PUT
@Produces("application/json")
public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@FormParam("unShareUser") String unShareUser,
@FormParam("roleName") String sharingRole) {
try {
boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup(
unShareUser, groupName, owner, sharingRole);
if (isUnShared) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
}
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
@PUT
@Produces("application/json")
public Response addSharing(@QueryParam("shareUser") String shareUser,
@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("roleName") String roleName, String[] permissions) {
try {
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole(
shareUser, groupName, owner, roleName, permissions);
if (isAdded) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@DELETE
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
@Produces("application/json")
public Response removeSharing(@QueryParam("userName") String userName,
@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("roleName") String roleName) {
try {
boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole(
groupName, owner, roleName);
if (isRemoved) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@GET
@Path("/owner/{owner}/name/{groupName}/share/roles")
@Produces("application/json")
public Response getRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@QueryParam("userName") String userName) {
try {
List<String> roles;
if (userName != null && !userName.isEmpty()) {
roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner);
} else {
roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
}
String[] rolesArray = new String[roles.size()];
roles.toArray(rolesArray);
return Response.status(Response.Status.OK).entity(rolesArray).build();
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@PUT
@Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles")
@Produces("application/json")
public Response setRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("userName") String userName, List<String> selectedRoles) {
try {
List<String> allRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
for (String role : allRoles) {
if (selectedRoles.contains(role)) {
DeviceMgtAPIUtils.getGroupManagementProviderService()
.shareGroup(userName, groupName, owner, role);
} else {
DeviceMgtAPIUtils.getGroupManagementProviderService()
.unshareGroup(userName, groupName, owner, role);
}
}
return Response.status(Response.Status.OK).build();
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@GET
@Path("/owner/{owner}/name/{groupName}/users")
@Produces("application/json")
public Response getUsers(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try {
List<GroupUser> users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers(
groupName, owner);
GroupUser[] usersArray = new GroupUser[users.size()];
users.toArray(usersArray);
return Response.status(Response.Status.OK).entity(usersArray).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@GET
@Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json")
public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@QueryParam("start") int startIdx, @QueryParam("length") int length) {
try {
PaginationResult paginationResult = DeviceMgtAPIUtils
.getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length);
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@GET
@Path("/owner/{owner}/name/{groupName}/devices/count")
@Produces("application/json")
public Response getDeviceCount(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try {
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner);
return Response.status(Response.Status.OK).entity(count).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@POST
@Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json")
public Response addDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
DeviceIdentifier deviceIdentifier) {
try {
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice(
deviceIdentifier, groupName, owner);
if (isAdded) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@DELETE
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}")
@Produces("application/json")
public Response removeDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice(
deviceIdentifier, groupName, owner);
if (isRemoved) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Override
@GET
@Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions")
@Produces("application/json")
public Response getPermissions(@PathParam("userName") String userName,
@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try {
String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService()
.getPermissions(userName, groupName, owner);
return Response.status(Response.Status.OK).entity(permissions).build();
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
}

@ -1,102 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.License;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This class represents license related operations.
*/
@SuppressWarnings("NonJaxWsWebServices")
public class LicenseImpl implements License {
private static Log log = LogFactory.getLog(LicenseImpl.class);
/**
* This method returns the license text related to a given device type and language code.
*
* @param deviceType Device type, ex: android, ios
* @param languageCode Language code, ex: en_US
* @return Returns the license text
*/
@GET
@Path ("{deviceType}/{languageCode}")
@Produces ({MediaType.APPLICATION_JSON})
public Response getLicense(@PathParam ("deviceType") String deviceType,
@PathParam("languageCode") String languageCode) {
org.wso2.carbon.device.mgt.common.license.mgt.License license;
ResponsePayload responsePayload;
try {
license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode);
if (license == null) {
return Response.status(HttpStatus.SC_NOT_FOUND).build();
}
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
messageFromServer("License for '" + deviceType + "' was retrieved successfully").
responseContent(license.getText()).
build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* This method is used to add license to a specific device type.
*
* @param deviceType Device type, ex: android, ios
* @param license License object
* @return Returns the acknowledgement for the action
*/
@POST
@Path ("{deviceType}")
public Response addLicense(@PathParam ("deviceType") String deviceType,
org.wso2.carbon.device.mgt.common.license.mgt.License license) {
ResponsePayload responsePayload;
try {
DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license);
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
messageFromServer("License added successfully for '" + deviceType + "' device type").
build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while adding license for '" + deviceType + "' device type";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
}

@ -1,275 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext;
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.Platform;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Operation related REST-API implementation.
*/
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"})
public class OperationImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Operation {
private static Log log = LogFactory.getLog(OperationImpl.class);
/* @deprecated */
@Override
@GET
public Response getAllOperations() {
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operations = dmService.getOperations(null);
} catch (OperationManagementException e) {
String msg = "Error occurred while fetching the operations for the device.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(operations).build();
}
@Override
@GET
@Path("paginate/{type}/{id}")
public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id,
@QueryParam("start") int startIdx, @QueryParam("length") int length,
@QueryParam("search") String search) {
PaginationResult operations;
DeviceManagementProviderService dmService;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
try {
deviceIdentifier.setType(type);
deviceIdentifier.setId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operations = dmService.getOperations(deviceIdentifier, paginationRequest);
} catch (OperationManagementException e) {
String msg = "Error occurred while fetching the operations for the device.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(operations).build();
}
@Override
@GET
@Path("{type}/{id}")
public Response getAllDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) {
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
DeviceManagementProviderService dmService;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
try {
deviceIdentifier.setType(type);
deviceIdentifier.setId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operations = dmService.getOperations(deviceIdentifier);
} catch (OperationManagementException e) {
String msg = "Error occurred while fetching the operations for the device.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(operations).build();
}
/* @deprecated */
@Override
@POST
public Response addOperation(DeviceOperationContext operationContext) {
DeviceManagementProviderService dmService;
ResponsePayload responseMsg = new ResponsePayload();
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
//TODO: Fix this properly later adding device type to be passed in when the task manage executes "addOperations()"
String type = null;
List<DeviceIdentifier> deviceIdentifiers = operationContext.getDevices();
if (deviceIdentifiers.size() > 0) {
type = deviceIdentifiers.get(0).getType();
}
Activity activity = dmService.addOperation(type, operationContext.getOperation(), operationContext.getDevices());
if (activity != null) {
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Operation has added successfully.");
}
return Response.status(Response.Status.CREATED).entity(activity).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while saving the operation";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@GET
@Path("{type}/{id}/apps")
public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) {
List<Application> applications;
ApplicationManagementProviderService appManagerConnector;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
try {
deviceIdentifier.setType(type);
deviceIdentifier.setId(id);
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier);
} catch (ApplicationManagementException e) {
String msg = "Error occurred while fetching the apps of the device.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.CREATED).entity(applications).build();
}
@Override
@POST
@Path("installApp/{tenantDomain}")
public Response installApplication(ApplicationWrapper applicationWrapper,
@PathParam("tenantDomain") String tenantDomain) {
ResponsePayload responseMsg = new ResponsePayload();
ApplicationManager appManagerConnector;
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
Activity activity = null;
try {
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
MobileApp mobileApp = applicationWrapper.getApplication();
if (applicationWrapper.getDeviceIdentifiers() != null) {
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
if (deviceIdentifier.getType().equals(Platform.android.toString())) {
operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp);
}
}
activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
}
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Authentication installation request has been sent to the device.");
return Response.status(Response.Status.CREATED).entity(activity).build();
} catch (ApplicationManagementException | MDMAPIException e) {
String msg = "Error occurred while saving the operation";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@POST
@Path("uninstallApp/{tenantDomain}")
public Response uninstallApplication(ApplicationWrapper applicationWrapper,
@PathParam("tenantDomain") String tenantDomain) {
ResponsePayload responseMsg = new ResponsePayload();
ApplicationManager appManagerConnector;
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
Activity activity = null;
try {
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
MobileApp mobileApp = applicationWrapper.getApplication();
if (applicationWrapper.getDeviceIdentifiers() != null) {
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
if (deviceIdentifier.getType().equals(Platform.android.toString())) {
operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp);
}
}
activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
}
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Authentication removal request has been sent to the device.");
return Response.status(Response.Status.CREATED).entity(activity).build();
} catch (ApplicationManagementException | MDMAPIException e) {
String msg = "Error occurred while saving the operation";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@GET
@Path("activity/{id}")
public Response getActivity( @PathParam("id") String id)
throws MDMAPIException {
Activity activity;
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
} catch (OperationManagementException e) {
String msg = "Error occurred while fetching the activity for the supplied id.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
return Response.status(Response.Status.OK).entity(activity).build();
}
@Override
@GET
@Path("activity/after/{timestamp}")
public Response getActivityUpdatedAfter(@PathParam("timestamp") String timestamp)
throws MDMAPIException {
List<Activity> activities;
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activities = dmService.getActivitiesUpdatedAfter(Long.parseLong(timestamp));
} catch (OperationManagementException e) {
String msg = "Error occurred while fetching the activities updated after given time stamp.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
return Response.status(Response.Status.OK).entity(activities).build();
}
}

@ -1,501 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
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.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class PolicyImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Policy {
private static Log log = LogFactory.getLog(PolicyImpl.class);
@Override
@POST
@Path("inactive-policy")
public Response addPolicy(PolicyWrapper policyWrapper) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload();
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.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());
return addPolicy(policyManagementService, responseMsg, policy);
}
@Override
@POST
@Path("active-policy")
public Response addActivePolicy(PolicyWrapper policyWrapper) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload();
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.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());
policy.setActive(true);
return addPolicy(policyManagementService, responseMsg, policy);
}
private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg,
org.wso2.carbon.policy.mgt.common.Policy policy) {
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)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (DeviceAccessAuthorizationException e) {
String msg = "Device access authorization exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.addPolicy(policy);
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Policy has been added successfully.");
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getAllPolicies() {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<org.wso2.carbon.policy.mgt.common.Policy> policies;
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicies();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending all retrieved device policies.");
responsePayload.setResponseContent(policies);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("{id}")
public Response getPolicy(@PathParam("id") int policyId) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
final org.wso2.carbon.policy.mgt.common.Policy policy;
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policy = policyAdministratorPoint.getPolicy(policyId);
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
if (policy == null){
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
responsePayload.setMessageFromServer("Policy for ID " + policyId + " not found.");
return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending all retrieved device policies.");
responsePayload.setResponseContent(policy);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@GET
@Path("count")
public Response getPolicyCount() {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
Integer count = policyAdministratorPoint.getPolicyCount();
return Response.status(Response.Status.OK).entity(count).build();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@PUT
@Path("{id}")
public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload();
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
policy.setPolicyName(policyWrapper.getPolicyName());
policy.setId(policyId);
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());
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.updatePolicy(policy);
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Policy has been updated successfully.");
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception in policy update.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@PUT
@Path("priorities")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<org.wso2.carbon.policy.mgt.common.Policy> policiesToUpdate =
new ArrayList<>(priorityUpdatedPolicies.size());
int i;
for (i = 0; i < priorityUpdatedPolicies.size(); i++) {
org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy();
policyObj.setId(priorityUpdatedPolicies.get(i).getId());
policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority());
policiesToUpdate.add(policyObj);
}
boolean policiesUpdated;
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate);
} catch (PolicyManagementException e) {
String msg = "Exception in updating policy priorities.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
if (policiesUpdated) {
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy Priorities successfully updated.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
} else {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Policy priorities did not update. Bad Request.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
}
}
@Override
@POST
@Path("bulk-remove")
@Consumes("application/json")
@Produces("application/json")
public Response bulkRemovePolicy(List<Integer> policyIds) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
boolean policyDeleted = true;
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
for(int i : policyIds) {
org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i);
if(!pap.deletePolicy(policy)){
policyDeleted = false;
}
}
} catch (PolicyManagementException e) {
String msg = "Exception in deleting policies.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
if (policyDeleted) {
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policies have been successfully deleted.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
} else {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Policy does not exist.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
}
}
@Override
@PUT
@Produces("application/json")
@Path("activate")
public Response activatePolicy(List<Integer> policyIds) {
try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP();
for(int i : policyIds) {
pap.activatePolicy(i);
}
} catch (PolicyManagementException e) {
String msg = "Exception in activating policies.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Selected policies have been successfully activated.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@PUT
@Produces("application/json")
@Path("inactivate")
public Response inactivatePolicy(List<Integer> policyIds) throws MDMAPIException {
try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP();
for(int i : policyIds) {
pap.inactivatePolicy(i);
}
} catch (PolicyManagementException e) {
String msg = "Exception in inactivating policies.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Selected policies have been successfully inactivated.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@PUT
@Produces("application/json")
@Path("apply-changes")
public Response applyChanges() {
try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.publishChanges();
} catch (PolicyManagementException e) {
String msg = "Exception in applying changes.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Changes have been successfully updated.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@GET
@Path("start-task/{milliseconds}")
public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
taskScheduleService.startTask(monitoringFrequency);
} catch (PolicyMonitoringTaskException e) {
String msg = "Policy Management related exception.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy monitoring service started successfully.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@GET
@Path("update-task/{milliseconds}")
public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
taskScheduleService.updateTask(monitoringFrequency);
} catch (PolicyMonitoringTaskException e) {
String msg = "Policy Management related exception.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy monitoring service updated successfully.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@GET
@Path("stop-task")
public Response stopTaskService() {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
taskScheduleService.stopTask();
} catch (PolicyMonitoringTaskException e) {
String msg = "Policy Management related exception.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy monitoring service stopped successfully.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
@Override
@GET
@Path("{type}/{id}")
public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) {
try {
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier);
return Response.status(Response.Status.OK).entity(complianceData).build();
} catch (PolicyComplianceException e) {
String msg = "Error occurred while getting the compliance data.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@GET
@Path("{type}/{id}/active-policy")
public Response getDeviceActivePolicy(@PathParam("type") String type, @PathParam("id") String id) {
try {
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService
.getAppliedPolicyToDevice(deviceIdentifier);
return Response.status(Response.Status.OK).entity(policy).build();
} catch (PolicyManagementException e) {
String msg = "Error occurred while getting the current policy.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/device-group/{user}")
public Response getDeviceGroupsRelatedToPolicies(@PathParam("user") String userName) {
try {
List<DeviceGroupWrapper> groupWrappers = new ArrayList<>();
GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
List<DeviceGroup> deviceGroups = service.getGroups(userName);
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
for (DeviceGroup dg : deviceGroups) {
DeviceGroupWrapper gw = new DeviceGroupWrapper();
gw.setId(dg.getId());
gw.setOwner(dg.getOwner());
gw.setName(dg.getName());
gw.setTenantId(tenantId);
groupWrappers.add(gw);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending all retrieved device groups.");
responsePayload.setResponseContent(groupWrappers);
return Response.status(HttpStatus.SC_OK).entity(groupWrappers).build();
} catch (GroupManagementException e) {
String error = "Error occurred while getting the groups related to users for policy.";
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
}
}
}

@ -1,87 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.Profile;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@SuppressWarnings("NonJaxWsWebServices")
public class ProfileImpl implements Profile{
private static Log log = LogFactory.getLog(ProfileImpl.class);
@POST
public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
profile = pap.addProfile(profile);
return Response.status(Response.Status.OK).entity(profile).build();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@POST
@Path("{id}")
public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile,
@PathParam("id") String profileId) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload();
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.updateProfile(profile);
responseMsg.setMessageFromServer("Profile has been updated successfully.");
return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@DELETE
@Path("{id}")
public Response deleteProfile(@PathParam("id") int profileId) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload();
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP();
org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId);
pap.deleteProfile(profile);
responseMsg.setMessageFromServer("Profile has been deleted successfully.");
return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (PolicyManagementException e) {
String msg = "Policy Management related exception";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -1,450 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
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;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class RoleImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Role {
private static Log log = LogFactory.getLog(RoleImpl.class);
/**
* Get user roles (except all internal roles) from system.
*
* @return A list of users
*/
@Override
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getAllRoles() {
List<String> filteredRoles;
try {
filteredRoles = getRolesFromUserStore();
} catch (MDMAPIException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
responsePayload.setResponseContent(filteredRoles);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get user roles by user store(except all internal roles) from system.
*
* @return A list of users
*/
@Override
@GET
@Path("{userStore}")
@Produces({MediaType.APPLICATION_JSON})
public Response getRolesOfUserStore(@PathParam("userStore") String userStore) {
String[] roles;
try {
AbstractUserStoreManager abstractUserStoreManager =
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
roles = abstractUserStoreManager.getRoleNames(userStore + "/*", -1, false, true, true);
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of user roles.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
// removing all internal roles and roles created for Service-providers
List<String> filteredRoles = new ArrayList<>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
filteredRoles.add(role);
}
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
responsePayload.setResponseContent(filteredRoles);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get user roles by providing a filtering criteria(except all internal roles & system roles) from system.
*
* @return A list of users
*/
@Override
@GET
@Path("search")
@Produces({MediaType.APPLICATION_JSON})
public Response getMatchingRoles(@QueryParam("filter") String filter) {
String[] roles;
try {
AbstractUserStoreManager abstractUserStoreManager =
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles using filter : " + filter);
}
roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true);
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
// removing all internal roles and roles created for Service-providers
List<String> filteredRoles = new ArrayList<>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
filteredRoles.add(role);
}
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All matching user roles were successfully retrieved.");
responsePayload.setResponseContent(filteredRoles);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get role permissions.
*
* @return list of permissions
*/
@Override
@GET
@Path("permissions")
@Produces({MediaType.APPLICATION_JSON})
public Response getPermissions(@QueryParam("rolename") String roleName) {
try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
final UIPermissionNode rolePermissions;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
}
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All permissions retrieved");
responsePayload.setResponseContent(rolePermissions);
return Response.status(Response.Status.OK).entity(responsePayload).build();
} catch (UserAdminException | MDMAPIException e) {
String msg = "Error occurred while retrieving the user role";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Get user role of the system
*
* @return user role
*/
@Override
@GET
@Path("role")
@Produces({MediaType.APPLICATION_JSON})
public Response getRole(@QueryParam("rolename") String roleName) {
RoleWrapper roleWrapper = new RoleWrapper();
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
}
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
if (userStoreManager.isExistingRole(roleName)) {
roleWrapper.setRoleName(roleName);
roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName));
// Get the permission nodes and hand picking only device management and login perms
final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
ArrayList<String> permList = new ArrayList<>();
iteratePermissions(rolePermissions, permList);
roleWrapper.setPermissionList(rolePermissions);
String[] permListAr = new String[permList.size()];
roleWrapper.setPermissions(permList.toArray(permListAr));
}
} catch (UserStoreException | UserAdminException | MDMAPIException e) {
String msg = "Error occurred while retrieving the user role";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
responsePayload.setResponseContent(roleWrapper);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy)
throws UserAdminException {
final UIPermissionNode rolePermissions =
userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2];
for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) {
if (permissionNode.getResourcePath().equals("/permission/admin")) {
for (UIPermissionNode node : permissionNode.getNodeList()) {
if (node.getResourcePath().equals("/permission/admin/device-mgt")) {
deviceMgtPermissions[0] = node;
} else if (node.getResourcePath().equals("/permission/admin/login")) {
deviceMgtPermissions[1] = node;
}
}
}
}
rolePermissions.setNodeList(deviceMgtPermissions);
return rolePermissions;
}
/**
* API is used to persist a new Role
*
* @param roleWrapper for role
* @return response
*/
@Override
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response addRole(RoleWrapper roleWrapper) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Persisting the role to user store");
}
Permission[] permissions = null;
if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) {
permissions = new Permission[roleWrapper.getPermissions().length];
for (int i = 0; i < permissions.length; i++) {
String permission = roleWrapper.getPermissions()[i];
permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION);
}
}
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
} catch (UserStoreException | MDMAPIException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).build();
}
/**
* API is used to update a role Role
*
* @param roleWrapper for role
* @return response
*/
@Override
@PUT
@Produces({MediaType.APPLICATION_JSON})
public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) {
String newRoleName = roleWrapper.getRoleName();
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
if (log.isDebugEnabled()) {
log.debug("Updating the role to user store");
}
if (newRoleName != null && !roleName.equals(newRoleName)) {
userStoreManager.updateRoleName(roleName, newRoleName);
}
if (roleWrapper.getUsers() != null) {
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)),
Arrays.asList(roleWrapper.getUsers()));
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
.getObjectsToAdd().size()]);
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
.getObjectsToRemove().size()]);
userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd);
}
if (roleWrapper.getPermissions() != null) {
// Delete all authorizations for the current role before authorizing the permission tree
authorizationManager.clearRoleAuthorization(roleName);
if (roleWrapper.getPermissions().length > 0) {
for (int i = 0; i < roleWrapper.getPermissions().length; i++) {
String permission = roleWrapper.getPermissions()[i];
authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION);
}
}
}
} catch (UserStoreException | MDMAPIException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).build();
}
/**
* API is used to delete a role and authorizations
*
* @param roleName to delete
* @return response
*/
@Override
@DELETE
@Produces({MediaType.APPLICATION_JSON})
public Response deleteRole(@QueryParam("rolename") String roleName) {
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
if (log.isDebugEnabled()) {
log.debug("Deleting the role in user store");
}
userStoreManager.deleteRole(roleName);
// Delete all authorizations for the current role before deleting
authorizationManager.clearRoleAuthorization(roleName);
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while deleting the role: " + roleName;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).build();
}
/**
* API is used to update users of a role
*
* @param roleName to update
* @param userList of the users
* @return response
*/
@Override
@PUT
@Path("users")
@Produces({MediaType.APPLICATION_JSON})
public Response updateUsers(@QueryParam("rolename") String roleName, List<String> userList) {
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Updating the users of a role");
}
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)),
userList);
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
.getObjectsToAdd().size()]);
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
.getObjectsToRemove().size()]);
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while saving the users of the role: " + roleName;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).build();
}
private ArrayList<String> iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList<String> list) {
for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) {
list.add(permissionNode.getResourcePath());
if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) {
iteratePermissions(permissionNode, list);
}
}
return list;
}
/**
* This method is used to retrieve the role count of the system.
*
* @return returns the count.
*/
@Override
@GET
@Path("count")
public Response getRoleCount() {
try {
List<String> filteredRoles = getRolesFromUserStore();
Integer count = filteredRoles.size();
return Response.status(Response.Status.OK).entity(count).build();
} catch (MDMAPIException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
}
}
private List<String> getRolesFromUserStore() throws MDMAPIException {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] roles;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
roles = userStoreManager.getRoleNames();
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of user roles.";
throw new MDMAPIException(msg, e);
}
// removing all internal roles, roles created for Service-providers and application related roles.
List<String> filteredRoles = new ArrayList<>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith("Application/"))) {
filteredRoles.add(role);
}
}
return filteredRoles;
}
}

@ -1,763 +0,0 @@
/*
* 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.api.impl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
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.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
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.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
/**
* This class represents the JAX-RS services of User related functionality.
*/
@SuppressWarnings("NonJaxWsWebServices")
public class UserImpl implements org.wso2.carbon.device.mgt.jaxrs.api.User {
private static final String ROLE_EVERYONE = "Internal/everyone";
private static Log log = LogFactory.getLog(UserImpl.class);
/**
* Method to add user to emm-user-store.
*
* @param userWrapper Wrapper object representing input json payload
* @return {Response} Status of the request wrapped inside Response object
*/
@Override
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response addUser(UserWrapper userWrapper) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
// if user already exists
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() +
" already exists. Therefore, request made to add user was refused.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
responsePayload.
setMessageFromServer("User by username: " + userWrapper.getUsername() +
" already exists. Therefore, request made to add user was refused.");
return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
} else {
String initialUserPassword = generateInitialUserPassword();
Map<String, String> defaultUserClaims =
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
userWrapper.getEmailAddress());
// calling addUser method of carbon user api
userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword,
userWrapper.getRoles(), defaultUserClaims, null);
// invite newly added user to enroll device
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.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" was successfully added.");
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Method to get user information from emm-user-store.
*
* @param username User-name of the user
* @return {Response} Status of the request wrapped inside Response object.
*/
@Override
@GET
@Path("view")
@Produces({MediaType.APPLICATION_JSON})
public Response getUser(@QueryParam("username") String username) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) {
UserWrapper user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
// Outputting debug message upon successful retrieval of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was found.");
}
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("User information was retrieved successfully.");
responsePayload.setResponseContent(user);
return Response.status(Response.Status.OK).entity(responsePayload).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Exception in trying to retrieve user by username: " + username;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Update user in user store
*
* @param userWrapper Wrapper object representing input json payload
* @return {Response} Status of the request wrapped inside Response object.
*/
@Override
@PUT
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
Map<String, String> defaultUserClaims =
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
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"));
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
}
List<String> currentRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername());
List<String> newRoles = Arrays.asList(userWrapper.getRoles());
List<String> rolesToAdd = new ArrayList<>(newRoles);
List<String> rolesToDelete = new ArrayList<>();
for (String role : currentRoles) {
if (newRoles.contains(role)) {
rolesToAdd.remove(role);
} else {
rolesToDelete.add(role);
}
}
rolesToDelete.remove(ROLE_EVERYONE);
userStoreManager.updateRoleListOfUser(userWrapper.getUsername(),
rolesToDelete.toArray(new String[rolesToDelete.size()]),
rolesToAdd.toArray(new String[rolesToAdd.size()]));
userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" was successfully updated.");
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
} else {
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() +
" doesn't exists. Therefore, request made to update user was refused.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
responsePayload.
setMessageFromServer("User by username: " + userWrapper.getUsername() +
" doesn't exists. Therefore, request made to update user was refused.");
return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
}
} catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) {
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Private method to be used by addUser() to
* generate an initial user password for a user.
* This will be the password used by a user for his initial login to the system.
*
* @return {string} Initial User Password
*/
private String generateInitialUserPassword() {
int passwordLength = 6;
//defining the pool of characters to be used for initial password generation
String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numericCharset = "0123456789";
Random randomGenerator = new Random();
String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
int totalCharsetLength = totalCharset.length();
StringBuilder initialUserPassword = new StringBuilder();
for (int i = 0; i < passwordLength; i++) {
initialUserPassword
.append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength)));
}
if (log.isDebugEnabled()) {
log.debug("Initial user password is created for new user: " + initialUserPassword);
}
return initialUserPassword.toString();
}
/**
* Method to build default user claims.
*
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
* @return {Object} Default user claims to be provided
*/
private Map<String, String> buildDefaultUserClaims(String firstname, String lastname, String emailAddress) {
Map<String, String> defaultUserClaims = new HashMap<>();
defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname);
defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname);
defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress);
if (log.isDebugEnabled()) {
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
}
return defaultUserClaims;
}
/**
* Method to remove user from emm-user-store.
*
* @param username Username of the user
* @return {Response} Status of the request wrapped inside Response object.
*/
@Override
@DELETE
@Produces({MediaType.APPLICATION_JSON})
public Response removeUser(@QueryParam("username") String username) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) {
// if user already exists, trying to remove user
userStoreManager.deleteUser(username);
// Outputting debug message upon successful removal of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer(
"User by username: " + username + " was successfully removed.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for removal.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist for removal.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Exception in trying to remove user by username: " + username;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* get all the roles except for the internal/xxx and application/xxx
*
* @param userStoreManager User Store Manager associated with the currently logged in user
* @param username Username of the currently logged in user
* @return the list of filtered roles
*/
private List<String> getFilteredRoles(UserStoreManager userStoreManager, String username) {
String[] roleListOfUser = new String[0];
try {
roleListOfUser = userStoreManager.getRoleListOfUser(username);
} catch (UserStoreException e) {
e.printStackTrace();
}
List<String> filteredRoles = new ArrayList<>();
for (String role : roleListOfUser) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
filteredRoles.add(role);
}
}
return filteredRoles;
}
/**
* Get user's roles by username
*
* @param username Username of the user
* @return {Response} Status of the request wrapped inside Response object.
*/
@Override
@GET
@Path("roles")
@Produces({MediaType.APPLICATION_JSON})
public Response getRolesOfUser(@QueryParam("username") String username) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) {
responsePayload.setResponseContent(Collections.singletonList(getFilteredRoles(userStoreManager, username)));
// Outputting debug message upon successful removal of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer(
"User roles obtained for user " + username);
return Response.status(Response.Status.OK).entity(responsePayload).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for role retrieval.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist for role retrieval.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Exception in trying to retrieve roles for user by username: " + username;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Get the list of all users with all user-related info.
*
* @return A list of users
*/
@Override
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getAllUsers() {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information");
}
List<UserWrapper> userList;
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*", -1);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get the list of all users with all user-related info.
*
* @return A list of users
*/
@Override
@GET
@Path("{filter}")
@Produces({MediaType.APPLICATION_JSON})
public Response getMatchingUsers(@PathParam("filter") String filter) {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information using the filter : " + filter);
}
List<UserWrapper> userList;
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers(filter + "*", -1);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get the list of user names in the system.
*
* @return A list of user names.
*/
@Override
@GET
@Path("view-users")
public Response getAllUsersByUsername(@QueryParam("username") String userName) {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users by name");
}
List<UserWrapper> userList;
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get the list of user names in the system.
*
* @return A list of user names.
*/
@Override
@GET
@Path("users-by-username")
public Response getAllUserNamesByUsername(@QueryParam("username") String userName) {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users by name");
}
List<String> userList;
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
userList = new ArrayList<>(users.length);
Collections.addAll(userList, users);
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Gets a claim-value from user-store.
*
* @param username Username of the user
* @param claimUri required ClaimUri
* @return claim value
*/
private String getClaimValue(String username, String claimUri) throws MDMAPIException {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
try {
return userStoreManager.getUserClaimValue(username, claimUri, null);
} catch (UserStoreException e) {
throw new MDMAPIException("Error occurred while retrieving value assigned to the claim '" +
claimUri + "'", e);
}
}
/**
* Method used to send an invitation email to a new user to enroll a device.
*
* @param username Username of the user
*/
private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Sending invitation mail to user by username: " + username);
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
tenantDomain = "";
}
if (!username.contains("/")) {
username = "/" + username;
}
String[] usernameBits = username.split("/");
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
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("password", password);
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
try {
deviceManagementProviderService.sendRegistrationEmail(metaInfo);
} catch (DeviceManagementException e) {
String msg = "Error occurred while sending registration email to user '" + username + "'";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* Method used to send an invitation email to a existing user to enroll a device.
*
* @param usernames Username list of the users to be invited
*/
@Override
@POST
@Path("email-invitation")
@Produces({MediaType.APPLICATION_JSON})
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) {
if (log.isDebugEnabled()) {
log.debug("Sending enrollment invitation mail to existing user.");
}
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
try {
for (String username : usernames) {
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
Properties props = new Properties();
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("username", username);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
deviceManagementProviderService.sendEnrolmentInvitation(metaInfo);
}
} catch (DeviceManagementException | MDMAPIException e) {
String msg = "Error occurred while inviting user to enrol their device";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Email invitation was successfully sent to user.");
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
/**
* Get a list of devices based on the username.
*
* @param username Username of the device owner
* @return A list of devices
*/
@Override
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("devices")
public Response getAllDeviceOfUser(@QueryParam("username") String username,
@QueryParam("start") int startIdx, @QueryParam("length") int length) {
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
if (length > 0) {
PaginationRequest request = new PaginationRequest(startIdx, length);
request.setOwner(username);
return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(request)).build();
}
return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(username)).build();
} catch (DeviceManagementException e) {
String msg = "Device management error";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* This method is used to retrieve the user count of the system.
*
* @return returns the count.
* @
*/
@Override
@GET
@Path("count")
public Response getUserCount() {
try {
String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1);
Integer count = 0;
if (users != null) {
count = users.length;
}
return Response.status(Response.Status.OK).entity(count).build();
} catch (UserStoreException | MDMAPIException e) {
String msg =
"Error occurred while retrieving the list of users that exist within the current tenant";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* API is used to update roles of a user
*
* @param username
* @param userList
* @return
* @
*/
@Override
@PUT
@Path("{roleName}/users")
@Produces({MediaType.APPLICATION_JSON})
public Response updateRoles(@PathParam("roleName") String username, List<String> userList) {
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Updating the roles of a user");
}
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)),
userList);
final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]);
final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]);
userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd);
} catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while saving the roles for user: " + username;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
return Response.status(Response.Status.OK).build();
}
/**
* Method to change the user password.
*
* @param credentials Wrapper object representing user credentials.
* @return {Response} Status of the request wrapped inside Response object.
* @
*/
@Override
@POST
@Path("change-password")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response resetPassword(UserCredentialWrapper credentials) {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials);
}
/**
* Method to change the user password.
*
* @param credentials Wrapper object representing user credentials.
* @return {Response} Status of the request wrapped inside Response object.
* @
*/
@Override
@POST
@Path("reset-password")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response resetPasswordByAdmin(UserCredentialWrapper credentials) {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials);
}
}

@ -1,106 +0,0 @@
/*
* 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.api.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
/**
* This class builds Credential modification related Responses
*/
public class CredentialManagementResponseBuilder {
private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class);
/**
* Builds the response to change the password of a user
* @param credentials - User credentials
* @return Response Object
*/
public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) {
ResponsePayload responsePayload = new ResponsePayload();
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"));
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("UserImpl password by username: " + credentials.getUsername() +
" was successfully changed.");
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
} catch (UserStoreException e) {
log.error(e.getMessage(), e);
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Old password does not match.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
} catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() +
". The Character Encoding is not supported.";
log.error(errorMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
} catch (MDMAPIException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
}
}
/**
* Builds the response to reset the password of a user
* @param credentials - User credentials
* @return Response Object
*/
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String(
decodedNewPassword, "UTF-8"));
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("UserImpl password by username: " + credentials.getUsername() +
" was successfully changed.");
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
} catch (UserStoreException e) {
log.error(e.getMessage(), e);
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Could not change the password.");
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
} catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() +
". The Character Encoding is not supported.";
log.error(errorMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
} catch (MDMAPIException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
}
}
}

@ -1,111 +0,0 @@
/*
* 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.api.util;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.AppStoreApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.EnterpriseApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.RemoveApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.WebClip;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import java.util.Properties;
/**
* This class contains the all the operations related to IOS.
*/
public class MDMIOSOperationUtil {
/**
* This method is used to create Install Authentication operation.
*
* @param application MobileApp application
* @return operation
* @throws MDMAPIException
*
*/
public static Operation createInstallAppOperation(MobileApp application) throws MDMAPIException {
ProfileOperation operation = new ProfileOperation();
switch (application.getType()) {
case ENTERPRISE:
EnterpriseApplication enterpriseApplication =
new EnterpriseApplication();
enterpriseApplication.setBundleId(application.getId());
enterpriseApplication.setIdentifier(application.getIdentifier());
enterpriseApplication.setManifestURL(application.getLocation());
Properties properties = application.getProperties();
enterpriseApplication.setPreventBackupOfAppData((Boolean) properties.
get(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP));
enterpriseApplication.setRemoveAppUponMDMProfileRemoval((Boolean) properties.
get(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_INSTALL_ENTERPRISE_APPLICATION);
operation.setPayLoad(enterpriseApplication.toJSON());
operation.setType(Operation.Type.COMMAND);
break;
case PUBLIC:
AppStoreApplication appStoreApplication =
new AppStoreApplication();
appStoreApplication.setRemoveAppUponMDMProfileRemoval((Boolean) application.getProperties().
get(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
appStoreApplication.setIdentifier(application.getIdentifier());
appStoreApplication.setPreventBackupOfAppData((Boolean) application.getProperties().
get(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP));
appStoreApplication.setBundleId(application.getId());
appStoreApplication.setiTunesStoreID((Integer) application.getProperties().
get(MDMAppConstants.IOSConstants.I_TUNES_ID));
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_INSTALL_STORE_APPLICATION);
operation.setType(Operation.Type.COMMAND);
operation.setPayLoad(appStoreApplication.toJSON());
break;
case WEBAPP:
WebClip webClip = new WebClip();
webClip.setIcon(application.getIconImage());
webClip.setIsRemovable(application.getProperties().
getProperty(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
webClip.setLabel(application.getProperties().
getProperty(MDMAppConstants.IOSConstants.LABEL));
webClip.setURL(application.getLocation());
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_INSTALL_WEB_APPLICATION);
operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(webClip.toJSON());
break;
}
return operation;
}
public static Operation createAppUninstallOperation(MobileApp application) throws MDMAPIException{
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_REMOVE_APPLICATION);
operation.setType(Operation.Type.PROFILE);
RemoveApplication removeApplication =
new RemoveApplication();
removeApplication.setBundleId(application.getIdentifier());
operation.setPayLoad(removeApplication.toJSON());
return operation;
}
}

@ -0,0 +1,59 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import java.util.ArrayList;
import java.util.List;
@ApiModel(value = "List of activities", description = "This contains a set of activities that matches a given " +
"criteria as a collection")
public class ActivityList extends BasePaginatedResult {
private List<Activity> activities;
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("activities")
public List<Activity> getList() {
return activities;
}
public void setList(List<Activity> activities) {
this.activities = activities;
}
@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(" devices: [").append(activities).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -0,0 +1,72 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
public class BasePaginatedResult {
private int count;
private String next;
private String previous;
/**
* Number of Devices returned.
*/
@ApiModelProperty(value = "Number of resources returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
}

@ -0,0 +1,56 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.Device;
import java.util.ArrayList;
import java.util.List;
public class DeviceList extends BasePaginatedResult {
private List<Device> devices = new ArrayList<>();
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices")
public List<Device> getList() {
return devices;
}
public void setList(List<Device> devices) {
this.devices = devices;
}
@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(" devices: [").append(devices).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -0,0 +1,77 @@
/*
* 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 javax.validation.constraints.NotNull;
@ApiModel(description = "")
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.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(description = "")
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,57 @@
/*
* 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.device.mgt.common.notification.mgt.Notification;
import java.util.List;
@ApiModel(value = "notificationList")
public class NotificationList extends BasePaginatedResult {
private List<Notification> notifications;
@JsonProperty("notifications")
@ApiModelProperty("notifications")
public List<Notification> getNotifications() {
return notifications;
}
public void setNotifications(List<Notification> notifications) {
this.notifications = notifications;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append(" count: ").append(getCount()).append(",");
sb.append(" next: ").append(getNext()).append(",");
sb.append(" previous: ").append(getPrevious()).append(",");
sb.append(" notifications: [").append(notifications).append("");
sb.append("]}");
return sb.toString();
}
}

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

@ -16,16 +16,26 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.exception;
package org.wso2.carbon.device.mgt.jaxrs.beans;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
public class BadRequestException extends WebApplicationException {
@ApiModel(value = "PasswordResetWrapper", description = "User credential is included in this class.")
public class PasswordResetWrapper {
public BadRequestException(Message message, MediaType mediaType) {
super(Response.status(Response.Status.BAD_REQUEST).entity(message).type(mediaType).build());
}
/*
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();
}
}

@ -20,22 +20,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 +42,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 +50,25 @@ 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 = "active", value = "If the value is true it indicates that the policy is active. "
+ "If the value is false it indicates that the policy is inactive", required = true)
private boolean active;
@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,36 +118,28 @@ public class PolicyWrapper {
this.ownershipType = ownershipType;
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
public List<String> getUsers() {
return users;
public boolean isActive() {
return active;
}
public void setUsers(List<String> users) {
this.users = users;
public void setActive(boolean active) {
this.active = active;
}
public int getTenantId() {
return tenantId;
public List<DeviceIdentifier> getDeviceIdentifiers() {
return deviceIdentifiers;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
public void setDeviceIdentifier(List<DeviceIdentifier> deviceIdentifiers) {
this.deviceIdentifiers = deviceIdentifiers;
}
public int getProfileId() {
return profileId;
public List<String> getUsers() {
return users;
}
public void setProfileId(int profileId) {
this.profileId = profileId;
public void setUsers(List<String> users) {
this.users = users;
}
}

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

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
@ -47,8 +46,9 @@ public class AppStoreApplication implements Serializable {
this.appIdentifier = appIdentifier;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
@ -28,36 +27,37 @@ import java.io.Serializable;
*/
public class EnterpriseApplication implements Serializable {
private String type;
private String url;
private String appIdentifier;
private String type;
private String url;
private String appIdentifier;
public String getAppIdentifier() {
return appIdentifier;
}
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String getType() {
return type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setUrl(String url) {
this.url = url;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}
}

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
@ -56,8 +55,9 @@ public class WebApplication implements Serializable {
this.type = type;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
@ -80,8 +79,9 @@ public class AppStoreApplication implements Serializable {
this.bundleId = bundleId;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
@ -76,7 +75,7 @@ public class EnterpriseApplication implements Serializable {
this.bundleId = bundleId;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
@ -35,8 +34,9 @@ public class RemoveApplication implements Serializable {
this.bundleId = bundleId;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
public class WebClip {
@ -69,7 +68,7 @@ public class WebClip {
this.isRemovable = isRemovable;
}
public String toJSON() throws MDMAPIException {
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}

@ -16,18 +16,17 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.api.common;
package org.wso2.carbon.device.mgt.jaxrs.common;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
@Produces({ "application/json", "application/xml" })
public class ErrorHandler implements ExceptionMapper<MDMAPIException> {
@Produces({ "application/json" })
public class ErrorHandler implements ExceptionMapper<Throwable> {
public Response toResponse(MDMAPIException exception) {
ErrorMessage errorMessage = new ErrorMessage();
errorMessage.setErrorMessage(exception.getErrorMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
public Response toResponse(Throwable e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.api.context;
package org.wso2.carbon.device.mgt.jaxrs.context;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;

@ -0,0 +1,45 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.exception;
public class UnknownApplicationTypeException extends Exception {
private static final long serialVersionUID = -3151279311929080299L;
public UnknownApplicationTypeException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public UnknownApplicationTypeException(String message, Throwable cause) {
super(message, cause);
}
public UnknownApplicationTypeException(String msg) {
super(msg);
}
public UnknownApplicationTypeException() {
super();
}
public UnknownApplicationTypeException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,174 @@
/*
* 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.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.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Activity related REST-API implementation.
*/
@API(name = "Activities", version = "1.0.0", context = "/devicemgt_admin/activities", tags = {"devicemgt_admin"})
@Path("/activities")
@Api(value = "Activity Info Provider", description = "Activity related information manipulation. For example operation details " +
"and responses from devices.")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ActivityInfoProviderService {
@GET
@Path("/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Retrieve details of a particular activity.",
notes = "This will return information of a particular activity i.e. meta information of an operation, " +
"etc; including the responses from the devices.",
tags = "Activity Info Provider")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Activity details are successfully fetched",
response = Activity.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 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 = 401,
message = ". \n Invalid request or validation error."),
@ApiResponse(
code = 404,
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"),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.",
response = ErrorResponse.class)
})
@Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"})
Response getActivity(
@ApiParam(
name = "id",
value = "Activity id of the operation/activity to be retrieved.",
required = true)
@PathParam("id") String id,
@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
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Retrieve details of a particular activity.",
notes = "This will return information of a particular activities i.e. meta information of operations, " +
"etc; including the responses from the devices which happened after given time.",
tags = "Activity Info Provider")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Activity details are successfully fetched",
response = ActivityList.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 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"),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.",
response = ErrorResponse.class)
})
@Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"})
Response getActivities(
@ApiParam(
name = "since",
value = "Validates if the requested variant has not been modified since the time specified, this " +
"should be provided in unix format in seconds.",
required = false)
@QueryParam("since") String since,
@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);
}

@ -0,0 +1,137 @@
/*
* 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.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.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* General Tenant Configuration REST-API.
*/
@API(name = "Configuration", version = "1.0.0", context = "/devicemgt_admin/configuration", tags = {"devicemgt_admin"})
@Path("/configuration")
@Api(value = "Configuration Management", description = "General Tenant Configuration management capabilities are exposed " +
"through this API")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ConfigurationManagementService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the general platform configurations.",
notes = "Get the general platform level configuration details.",
tags = "Configuration Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched general platform configuration.",
response = PlatformConfiguration.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 general " +
"platform configuration.",
response = ErrorResponse.class)
})
@Permission(scope = "configuration-view",
permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"})
Response getConfiguration(
@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);
@PUT
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update General Platform Configurations.",
notes = "This resource is used to update the general platform configuration.",
tags = "Configuration Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n General platform configuration has been updated successfully",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "URL of the updated general platform configuration."),
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while modifying general platform configuration.",
response = ErrorResponse.class)
})
@Permission(scope = "configuration-modify",
permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"})
Response updateConfiguration(
@ApiParam(
name = "configuration",
value = "The required properties to be updated in the platform configuration.",
required = true) PlatformConfiguration configuration);
}

@ -0,0 +1,81 @@
package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.Api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
//@Path("/dashboard")
//@Api(value = "Dashboard", description = "Dashboard related operations are described here.")
@SuppressWarnings("NonJaxWsWebServices")
public interface Dashboard {
// String CONNECTIVITY_STATUS = "connectivity-status";
// String POTENTIAL_VULNERABILITY = "potential-vulnerability";
// String NON_COMPLIANT_FEATURE_CODE = "non-compliant-feature-code";
// String PLATFORM = "platform";
// String OWNERSHIP = "ownership";
// // Constants related to pagination
// String PAGINATION_ENABLED = "pagination-enabled";
// String START_INDEX = "start";
// String RESULT_COUNT = "length";
//
// @GET
// @Path("device-count-overview")
// Response getOverviewDeviceCounts();
//
// @GET
// @Path("device-counts-by-potential-vulnerabilities")
// Response getDeviceCountsByPotentialVulnerabilities();
//
// @GET
// @Path("non-compliant-device-counts-by-features")
// Response getNonCompliantDeviceCountsByFeatures(@QueryParam(START_INDEX) int startIndex,
// @QueryParam(RESULT_COUNT) int resultCount);
//
// @GET
// @Path("device-counts-by-groups")
// Response getDeviceCountsByGroups(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
// @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
// @QueryParam(PLATFORM) String platform,
// @QueryParam(OWNERSHIP) String ownership);
//
// @GET
// @Path("feature-non-compliant-device-counts-by-groups")
// Response getFeatureNonCompliantDeviceCountsByGroups(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
// @QueryParam(PLATFORM) String platform,
// @QueryParam(OWNERSHIP) String ownership);
// @GET
// @Path("filtered-device-count-over-total")
// Response getFilteredDeviceCountOverTotal(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
// @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
// @QueryParam(PLATFORM) String platform,
// @QueryParam(OWNERSHIP) String ownership);
//
// @GET
// @Path("feature-non-compliant-device-count-over-total")
// Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
// @QueryParam(PLATFORM) String platform,
// @QueryParam(OWNERSHIP) String ownership);
//
// @GET
// @Path("devices-with-details")
// Response getDevicesWithDetails(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
// @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
// @QueryParam(PLATFORM) String platform,
// @QueryParam(OWNERSHIP) String ownership,
// @QueryParam(PAGINATION_ENABLED) String paginationEnabled,
// @QueryParam(START_INDEX) int startIndex,
// @QueryParam(RESULT_COUNT) int resultCount);
//
// @GET
// @Path("feature-non-compliant-devices-with-details")
// Response getFeatureNonCompliantDevicesWithDetails(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
// @QueryParam(PLATFORM) String platform,
// @QueryParam(OWNERSHIP) String ownership,
// @QueryParam(PAGINATION_ENABLED) String paginationEnabled,
// @QueryParam(START_INDEX) int startIndex,
// @QueryParam(RESULT_COUNT) int resultCount);
}

@ -0,0 +1,611 @@
/*
* 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.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.common.Device;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.policy.mgt.common.Policy;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Device related REST-API. This can be used to manipulated device related details.
*/
@API(name = "Device", version = "1.0.0", context = "/api/device-mgt/admin/devices", tags = {"devicemgt_admin"})
@Path("/devices")
@Api(value = "Device Management", description = "This API carries all device management related operations " +
"such as get all the available devices, etc.")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface DeviceManagementService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the list of devices enrolled with the system.",
notes = "Returns all devices enrolled with the system.",
tags = "Device Management")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
response = DeviceList.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 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.",
response = ErrorResponse.class)
})
@Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response getDevices(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.",
required = false)
@QueryParam("type") String type,
@ApiParam(
name = "user", value = "Username of owner of the devices.",
required = false)
@QueryParam("user") String user,
@ApiParam(
name = "roleName",
value = "Role name of the devices to be fetched.",
required = false)
@QueryParam("roleName") String roleName,
@ApiParam(
name = "ownership",
allowableValues = "BYOD, COPE",
value = "Ownership of the devices to be fetched registered under.",
required = false)
@QueryParam("ownership") String ownership,
@ApiParam(
name = "status",
value = "Enrollment status of devices to be fetched.",
required = false)
@QueryParam("status") String status,
@ApiParam(
name = "since",
value = "Last modified timestamp",
required = false)
@QueryParam("since") String since,
@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
@Path("/{type}/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get information of the requested device.",
notes = "Returns information of the requested device.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched information of the device.",
response = Device.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest " +
"version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No device is found under the provided type and id.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while retrieving information requested device.",
response = ErrorResponse.class)
})
@Permission(scope = "device-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getDevice(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.",
required = true)
@PathParam("type") String type,
@ApiParam(
name = "id",
value = "The device identifier of the device.",
required = true)
@PathParam("id") String id,
@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
@Path("/{type}/{id}/features")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get Feature Details of a Device",
notes = "WSO2 EMM features enable you to carry out many operations on a given device platform. " +
"Using this REST API you can get the features that can be carried out on a preferred device type," +
" such as iOS, Android or Windows.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n List of features of the device is returned",
response = Feature.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 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."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while retrieving feature list of the device.",
response = ErrorResponse.class)
})
@Permission(scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"})
Response getFeaturesOfDevice(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.",
required = true)
@PathParam("type") String type,
@ApiParam(
name = "id",
value = "The device identifier of the device.",
required = true)
@PathParam("id") String id,
@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);
@POST
@Path("/search-devices")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
consumes = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Advanced search for devices.",
notes = "Carry out an advanced search of devices.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Device list searched for has successfully been retrieved. Location header " +
"contains URL of newly enrolled device",
response = DeviceWrapper.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 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 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"),
@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 enrolling the device.",
response = ErrorResponse.class)
})
@Permission(scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/list"})
Response searchDevices(
@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 = "searchContext",
value = "List of search conditions.",
required = true)
SearchContext searchContext);
@GET
@Path("/{type}/{id}/applications")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting installed application details of a device.",
notes = "Get the list of applications that a device has subscribed.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n List of applications installed into the device is returned",
response = Application.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 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."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while retrieving installed application list of the device.",
response = ErrorResponse.class)
})
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"
})
Response getInstalledApplications(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.", required = true)
@PathParam("type") String type,
@ApiParam(
name = "id",
value = "The device identifier of the device.",
required = true)
@PathParam("id") String id,
@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,
@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
@Path("/{type}/{id}/operations")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting paginated details for operations on a device.",
notes = "You will carry out many operations on a device. In a situation where you wish to view the all" +
" the operations carried out on a device it is not feasible to show all the details on one page" +
" therefore the details are paginated.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n List of operations scheduled for the device is returned",
response = Operation.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 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."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while retrieving operation list scheduled for the device.",
response = ErrorResponse.class)
})
@Permission(scope = "operation-view", permissions = {
"/permission/admin/device-mgt/admin/devices/view",
"/permission/admin/device-mgt/user/devices/view"
})
Response getDeviceOperations(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.",
required = true)
@PathParam("type") String type,
@ApiParam(
name = "id",
value = "The device identifier of the device.",
required = true)
@PathParam("id") String id,
@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,
@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
@Path("/{type}/{id}/effective-policy")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the effective policy calculated for a device.",
notes = "When a device registers with WSO2 EMM a policy is enforced on the device. Initially the EMM " +
"filters the policies based on the Platform (device type), filters based on the device ownership" +
" type , filters based on the user role or name and finally the policy is enforced on the device.",
tags = "Device Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Effective policy calculated for the device is returned",
response = Policy.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 = 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 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."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while retrieving the effective policy calculated for the device.",
response = ErrorResponse.class)
})
Response getEffectivePolicyOfDevice(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.",
required = true)
@PathParam("type") String type,
@ApiParam(
name = "id",
value = "Device Identifier",
required = true)
@PathParam("id") String id,
@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
@Path("/types")
Response getDeviceTypes();
}

@ -0,0 +1,102 @@
/*
* 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.api;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
//@Path("/groups")
//@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_JSON)
public interface GroupManagementService {
// @GET
// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
// Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset,
// @QueryParam("limit") int limit);
//
// @POST
// @Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/user/groups/add"})
// Response createGroup(DeviceGroup group);
//
// @Path("/{groupName}")
// @GET
// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/view"})
// Response getGroup(@PathParam("groupName") String groupName);
//
// @Path("/{groupName}")
// @PUT
// @Permission(scope = "group-modify", permissions = {"/permission/admin/device-mgt/user/groups/update"})
// Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup);
//
// @Path("/{groupName}")
// @DELETE
// @Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/user/groups/remove"})
// Response deleteGroup(@PathParam("groupName") String groupName);
//
// @Path("/{groupName}/share-with-user")
// @POST
// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/share"})
// Response shareGroupWithUser(@PathParam("groupName") String groupName, String targetUser);
//
// @Path("/{groupName}/share-with-role")
// @POST
// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/share"})
// Response shareGroupWithRole(@PathParam("groupName") String groupName, String targetRole);
//
// @Path("/{groupName}/remove-share-with-user")
// @POST
// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/unshare"})
// Response removeShareWithUser(@PathParam("groupName") String groupName, String targetUser);
//
// @Path("/{groupName}/remove-share-with-role")
// @POST
// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/unshare"})
// Response removeShareWithRole(@PathParam("groupName") String groupName, String targetUser);
//
// @GET
// @Path("/{groupName}/users")
// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
// Response getUsersOfGroup(@PathParam("groupName") String groupName);
//
// @GET
// @Path("/{groupName}/devices")
// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/admin/groups/roles"})
// Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset,
// @QueryParam("limit") int limit);
//
// @POST
// @Path("/{groupName}/devices")
// @Produces("application/json")
// @Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/user/groups/devices/add"})
// Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier);
//
// @DELETE
// @Path("/{groupName}/devices")
// @Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/user/groups/devices/remove"})
// Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type,
// @QueryParam("id") String id);
}

@ -0,0 +1,118 @@
/*
* 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.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.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.jaxrs.NotificationContext;
import org.wso2.carbon.device.mgt.jaxrs.NotificationList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Notifications related REST-API.
*/
@API(name = "Device Notification Management API", version = "1.0.0", context = "/devicemgt_admin/notifications",
tags = {"devicemgt_admin"})
@Api(value = "Device Notification Management", description = "Device notification related operations can be found here.")
@Path("/notifications")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface NotificationManagementService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting all device notification details.",
notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using "
+ "this REST API",
tags = "Device Notification Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of notifications.",
response = NotificationList.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 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"),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the notification list.",
response = ErrorResponse.class)
})
@Permission(scope = "device-notification-view", permissions = {
"/permission/admin/device-mgt/admin/notifications/view",
"/permission/admin/device-mgt/user/notifications/view"
})
Response getNotifications(
@ApiParam(name = "status",
value = "Status of the notification.",
allowableValues = "NEW, CHECKED",
required = false)
@QueryParam("status") String status,
@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,
@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);
}

@ -0,0 +1,390 @@
/*
* 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.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;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Policy related REST-API. This can be used to manipulated policies and associate them with devices, users, roles,
* groups.
*/
@Api(value = "Device Policy Management", description = "This API carries all the necessary functionalities " +
"around device policy management")
@Path("/policies")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface PolicyManagementService {
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a new policy.",
notes = "This particular resource can be used to add a new policy, which will be created in in-active state.",
tags = "Device Policy Management")
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "Created. \n Policy has successfully been created",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the added policy."),
@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 = 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.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/add"})
Response addPolicy(
@ApiParam(
name = "policy",
value = "Policy details related to the operation.",
required = true) PolicyWrapper policy);
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get details of policies.",
responseContainer = "List",
notes = "Retrieve the details of all the policies that have been created in EMM.",
response = Policy.class,
tags = "Device Policy Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched policies.",
response = Policy.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 = 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."),
response = ErrorResponse.class)
})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getPolicies(
@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,
@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
@Path("/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get details of a policy.",
notes = "Retrieve the details of a given policy that has been created in EMM.",
response = Policy.class,
tags = "Device Policy Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the policy.",
response = Policy.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 has already the latest version of the requested resource."),
@ApiResponse(
code = 404,
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.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-view", permissions = {"/permission/admin/device-mgt/admin/policies/list"})
Response getPolicy(
@ApiParam(
name = "id",
value = "Policy identifier",
required = true)
@PathParam("id") int id,
@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);
@PUT
@Path("/{id}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update a policy.",
notes = "If you wish to make changes to an existing policy, that can be done by updating the policy using " +
"this resource.",
tags = "Device Policy Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Policy has been updated successfully",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the updated device."),
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
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.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"})
Response updatePolicy(
@ApiParam(
name = "id",
value = "The device identifier of the device.", required = true)
@PathParam("id") int id,
@ApiParam(
name = "policy",
value = "Policy details related to the operation.",
required = true) PolicyWrapper policy);
@POST
@Path("/remove-policy")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Remove multiple policies.",
notes = "In situations where you need to delete more than one policy you can do so using this API.",
tags = "Device Policy Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Policies have 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.",
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.",
response = ErrorResponse.class)
})
@Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/remove"})
Response removePolicies(
@ApiParam(
name = "policyIds",
value = "Policy id list to be deleted.",
required = true) List<Integer> policyIds);
@POST
@Path("/activate-policy")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Activating policies.",
notes = "Using the REST API command you are able to publish a policy in order to bring a policy that is " +
"in the inactive state to the active state.",
tags = "Device Policy Management")
@ApiResponses(
value = {
@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",
"/permission/admin/device-mgt/admin/policies/add"})
Response activatePolicies(
@ApiParam(name = "policyIds", value = "Policy ID list to be activated.",
required = true) List<Integer> policyIds);
@POST
@Path("/deactivate-policy")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Deactivating policies.",
notes = "Using the REST API command you are able to unpublish a policy in order to bring a policy that " +
"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 = 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",
"/permission/admin/device-mgt/admin/policies/add"})
Response deactivatePolicies(
@ApiParam(name = "policyIds", value = "Policy ID list to be deactivated.",
required = true) List<Integer> policyIds);
}

@ -0,0 +1,451 @@
/*
* 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.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.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;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@API(name = "Role", version = "1.0.0", context = "/devicemgt_admin/roles", tags = {"devicemgt_admin"})
@Path("/roles")
@Api(value = "Role Management", description = "Role management related operations can be found here.")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface RoleManagementService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the list of roles.",
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.",
tags = "Role Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested list of roles.",
response = RoleList.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 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.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {
"/permission/admin/device-mgt/admin/roles/list",
"/permission/admin/device-mgt/admin/users/view",
"/permission/admin/device-mgt/admin/policies/add",
"/permission/admin/device-mgt/admin/policies/update"})
Response getRoles(
@ApiParam(
name = "filter",
value = "Role name or a part of it to search.",
required = false)
@QueryParam("filter") String filter,
@ApiParam(
name = "user-store",
value = "From which user store the roles must be fetched.",
required = false)
@QueryParam("user-store") String userStoreName,
@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,
@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
@Path("/{roleName}/permissions")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting permission details of a role.",
notes = "In an organization an individual is associated a with set of responsibilities based on their " +
"role. In EMM you are able to configure permissions based on the responsibilities carried " +
"out by a role. Therefore if you wish to retrieve the permission details of a role, you can do " +
"so using this REST API.",
response = UIPermissionNode.class,
responseContainer = "List",
tags = "Role Management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the permission list of the given role.",
response = UIPermissionNode.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 = 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 = 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.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getPermissionsOfRole(
@ApiParam(
name = "roleName",
value = "Name of the role.",
required = true)
@PathParam("roleName") String roleName,
@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
@Path("/{roleName}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get details of a role.",
notes = "If you wish to get the details of a role in EMM, you can do so using this REST API.",
response = RoleWrapper.class,
tags = "Role Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested role.",
response = RoleWrapper.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 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 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.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getRole(
@ApiParam(
name = "roleName",
value = "Name of the role.",
required = true)
@PathParam("roleName") String roleName,
@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);
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a role.",
notes = "You are able to add a new role to EMM using the REST API.",
tags = "Role Management")
@ApiResponses(value = {
@ApiResponse(
code = 201,
message = "Created. \n Role has successfully been created",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the role added."),
@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 ErrorResponse. \n " +
"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(
@ApiParam(
name = "role",
value = "Details about the role to be added.",
required = true) RoleWrapper role);
@PUT
@Path("/{roleName}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update a role.",
notes = "There will be situations where you will need to update the role details, such as the permissions" +
" or the role name. In such situation you can update the role details.",
tags = "Role Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Role has been updated successfully",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "URL of the updated role."),
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateRole(
@ApiParam(
name = "roleName",
value = "Name of the role.",
required = true)
@PathParam("roleName") String roleName,
@ApiParam(
name = "role",
value = "Details about the role to be added.",
required = true) RoleWrapper role);
@DELETE
@Path("/{roleName}")
@ApiOperation(
httpMethod = "DELETE",
value = "Delete a role.",
notes = "In a situation when your Organization identifies that a specific role is no longer required you " +
"will need to remove the role details from EMM.",
tags = "Role Management")
@ApiResponses(value = {
@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.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"})
Response deleteRole(
@ApiParam(
name = "roleName",
value = "Name of the role to de deleted.",
required = true)
@PathParam("roleName") String roleName);
@PUT
@Path("/{roleName}/users")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Add users to a role.",
notes = "Defining the users to a role at the point of creating a new role is optional, " +
"therefore you are able to update the users that belong to a given role after you have created " +
"a role using this REST API." +
"Example: Your Organization hires 30 new engineers. Updating the role details for each user can " +
"be cumbersome, therefore you can define all the new employees that belong to the engineering " +
"role using this API.",
tags = "Role Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n User list of the role has been updated successfully",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "URL of the updated user list."),
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the user list of the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateUsersOfRole(
@ApiParam(
name = "roleName",
value = "Name of the role.",
required = true)
@PathParam("roleName") String roleName,
@ApiParam(
name = "users",
value = "List of usernames to be added.",
required = true) List<String> users);
}

@ -0,0 +1,465 @@
/*
* 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.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.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;
@API(name = "User Management API", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"})
@Path("/users")
@Api(value = "User Management", description = "User management related operations can be found here.")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface UserManagementService {
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a user.",
notes = "A new user can be added to the user management system via this resource",
tags = "User Management")
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "Created. \n User has successfully been created",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the role added."),
@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."),
@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.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"})
Response addUser(
@ApiParam(
name = "user",
value = "User related details.",
required = true) UserWrapper user);
@GET
@Path("/{username}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting details of a user.",
notes = "If you wish to get the details of a specific user that is registered with EMM,"
+ " you can do so using the REST API.",
response = UserWrapper.class,
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested role.",
response = UserWrapper.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 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 the requested user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"})
Response getUser(
@ApiParam(
name = "username",
value = "Username of the user to be fetched.",
required = true)
@PathParam("username") String username,
@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);
@PUT
@Path("/{username}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update details of a user",
notes = "There will be situations where you will want to update the user details. In such "
+ "situation you can update the user details using this REST API.",
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n User has been updated successfully",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "URL of the updated user."),
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource 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.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/update"})
Response updateUser(
@ApiParam(
name = "username",
value = "Username of the user to be updated.",
required = true)
@PathParam("username") String username,
@ApiParam(
name = "userData",
value = "User related details.",
required = true) UserWrapper userData);
@DELETE
@Path("/{username}")
@ApiOperation(
httpMethod = "DELETE",
value = "Deleting a user.",
notes = "In a situation where an employee leaves the organization you will need to remove the"
+ " user details from EMM. In such situations you can use this REST API to remove a user.",
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n User has successfully been removed"),
@ApiResponse(
code = 404,
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.",
response = ErrorResponse.class
)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/remove"})
Response removeUser(
@ApiParam(name = "username", value = "Username of the user to be deleted.", required = true)
@PathParam("username") String username);
@GET
@Path("/{username}/roles")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the role list of a user.",
notes = "A user can be assigned to one or more role in EMM. Using this REST API you are "
+ "able to get the role/roles a user is assigned to.",
response = String.class,
responseContainer = "List",
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the role list assigned to the user.",
response = String.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 = 404,
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.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"})
Response getRolesOfUser(
@ApiParam(name = "username", value = "Username of the user.", required = true)
@PathParam("username") String username);
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
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 = UserList.class,
responseContainer = "List",
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested role.",
response = UserList.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 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.",
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 = false)
@QueryParam("filter") String filter,
@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
@Path("/search/usernames")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Search for a username.",
notes = "If you are unsure of the "
+ "user name of a user and need to retrieve the details of a specific user, you can "
+ "search for that user by giving a character or a few characters in the username. "
+ "You will be given a list of users having the user name with the exact order of the "
+ "characters you provided.",
response = String.class,
responseContainer = "List",
tags = "User Management")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the username list that matches the given filter.",
response = String.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 username " +
"list that matches the given filter.",
response = ErrorResponse.class)
})
@Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"})
Response getUserNames(
@ApiParam(
name = "filter",
value = "Username/part of the user name to search.",
required = true)
@QueryParam("filter") String filter,
@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);
@PUT
@Path("/{username}/credentials")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
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")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Credentials of the user have been updated successfully"),
@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 = 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 credentials of the user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/login"})
Response resetPassword(
@ApiParam(
name = "username",
value = "Username of the user.",
required = true)
@PathParam("username") String username,
@ApiParam(
name = "credentials",
value = "Credential.",
required = true) OldPasswordResetWrapper credentials);
}

@ -0,0 +1,120 @@
/*
* 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.api.admin;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "Application", version = "1.0.0", context = "/devicemgt_admin/applications", tags = {"devicemgt_admin"})
@Path("/admin/applications")
@Api(value = "Application 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 ")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ApplicationManagementAdminService {
@POST
@Path("/install-application")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Application installation API.(Internal API)",
notes = "This is an internal API used for application installation on a device.",
response = Activity.class,
tags = "Application Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(
code = 202,
message = "OK. \n Install application operation will be delivered to the given devices",
response = Activity.class),
@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 processed does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while bulk issuing application installation operations upon " +
"a given set of devices.",
response = ErrorResponse.class)
})
Response installApplication(
@ApiParam(
name = "applicationWrapper",
value = "Application details of the application to be installed.",
required = true) ApplicationWrapper applicationWrapper);
@POST
@Path("/uninstall-application")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Application un-installation API.(Internal API)",
notes = "This is an internal API used for application un-installation on a device.",
response = Activity.class,
tags = "Application Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(
code = 202,
message = "OK. \n Uninstall application operation will be delivered to the provided devices",
response = Activity.class),
@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 processed does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while bulk issuing application un-installation operations upon " +
"a given set of devices.",
response = ErrorResponse.class)
})
Response uninstallApplication(
@ApiParam(
name = "applicationWrapper",
value = "Application details of the application to be uninstalled.",
required = true) ApplicationWrapper applicationWrapper);
}

@ -0,0 +1,118 @@
/*
* 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.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;
import javax.ws.rs.core.Response;
@API(name = "DeviceManagementAdmin", version = "1.0.0", context = "/devicemgt_admin/applications",
tags = {"devicemgt_admin"})
@Path("/admin/devices")
@Api(value = "Device 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 ")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface DeviceManagementAdminService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get devices by name.",
notes = "Get devices by name of the device and tenant that they belong to.",
response = Device.class,
responseContainer = "List",
tags = "Device Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
response = Device.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 = 401,
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.",
response = ErrorResponse.class)
})
Response getDevicesByName(
@ApiParam(
name = "name",
value = "Name of the device.",
required = true)
@QueryParam("name") String name,
@ApiParam(
name = "type",
value = "Type of the device.",
required = true)
@QueryParam("type") String type,
@ApiParam(
name = "tenant-domain",
value = "Name of the tenant.",
required = true)
@QueryParam("tenant-domain") String tenantDomain,
@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,
@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);
}

@ -0,0 +1,99 @@
/*
* 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.api.admin;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper;
import javax.ws.rs.*;
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 ")
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);
//
}

@ -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.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.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/admin/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "User 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 UserManagementAdminService {
@PUT
@Path("/{username}/credentials")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Change the user password.",
notes = "A user is able to change the password to secure their EMM profile via this REST API.",
tags = "User Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Credentials of the user have been updated successfully"),
@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 = 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 credentials of the user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/login"})
Response resetUserPassword(
@ApiParam(
name = "username",
value = "Username of the user.",
required = true)
@PathParam("username") String username,
@ApiParam(
name = "credentials",
value = "Credential.",
required = true) PasswordResetWrapper credentials);
}

@ -0,0 +1,140 @@
/*
* 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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService;
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.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Path("/activities")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ActivityProviderServiceImpl implements ActivityInfoProviderService {
private static final Log log = LogFactory.getLog(ActivityProviderServiceImpl.class);
@GET
@Override
@Path("/{id}")
public Response getActivity(@PathParam("id") String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
Activity activity;
DeviceManagementProviderService dmService;
try {
RequestValidationUtil.validateActivityId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
if (activity == null) {
throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setCode(404l)
.setMessage("No activity can be " +
"found upon the provided activity id '" + id + "'").build());
}
} catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode(500l)
.setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity(activity).build();
}
@GET
@Override
public Response getActivities(@QueryParam("since") String since, @QueryParam("offset") int offset,
@QueryParam("limit") int limit,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
long ifModifiedSinceTimestamp = 0;
long sinceTimestamp = 0;
long timestamp = 0;
boolean isIfModifiedSinceSet = false;
boolean isSinceSet = false;
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
Date ifSinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l)
.setMessage("Invalid date string is provided in 'If-Modified-Since' header").build());
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
isIfModifiedSinceSet = true;
timestamp = ifModifiedSinceTimestamp / 1000;
} else if (since != null && !since.isEmpty()) {
Date sinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l)
.setMessage("Invalid date string is provided in 'since' filter").build());
}
sinceTimestamp = sinceDate.getTime();
isSinceSet = true;
timestamp = sinceTimestamp / 1000;
}
List<Activity> activities;
ActivityList activityList = new ActivityList();
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset);
activityList.setList(activities);
int count = dmService.getActivityCountUpdatedAfter(timestamp);
activityList.setCount(count);
if (activities == null || activities.size() == 0) {
if (isIfModifiedSinceSet) {
return Response.status(Response.Status.NOT_MODIFIED).entity(
"No activities " + "after the time provided in 'If-Modified-Since' header")
.build();
} else if (isSinceSet) {
return Response.status(Response.Status.NOT_MODIFIED).entity(
"No activities " + "after the time provided in 'since' filter").build();
}
throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setCode(404l)
.setMessage("No activities " + "found.").build());
}
} catch (OperationManagementException e) {
String msg
= "ErrorResponse occurred while fetching the activities updated after given time stamp.";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode(500l)
.setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity(activityList).build();
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save