revert-70aa11f8
dilanua 9 years ago
commit d5950afe7a

@ -105,6 +105,10 @@
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.lcm</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
</dependencies>

@ -30,7 +30,8 @@ import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import javax.servlet.ServletContext;
import java.io.IOException;
@ -51,13 +52,16 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) {
String profile = System.getProperty(DeviceManagementConstants.Common.PROPERTY_PROFILE);
if ((profile.equalsIgnoreCase(DeviceManagementConstants.Common.PROFILE_DT_WORKER) ||
profile.equalsIgnoreCase(DeviceManagementConstants.Common.PROFILE_DEFAULT)) && isManagedApi) {
try {
AnnotationUtil annotationUtil = new AnnotationUtil(context);
Set<String> annotatedAPIClasses = annotationUtil.
AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
Set<String> annotatedAPIClasses = annotationProcessor.
scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext,
List<APIResourceConfiguration> apiDefinitions = annotationProcessor.extractAPIInfo(servletContext,
annotatedAPIClasses);
for (APIResourceConfiguration apiDefinition : apiDefinitions) {

@ -32,6 +32,8 @@ import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.deviceType.DTConfiguration;
import javax.servlet.ServletContext;
import javax.ws.rs.*;
@ -47,9 +49,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class AnnotationUtil {
public class AnnotationProcessor {
private static final Log log = LogFactory.getLog(AnnotationUtil.class);
private static final Log log = LogFactory.getLog(AnnotationProcessor.class);
private static final String PACKAGE_ORG_APACHE = "org.apache";
private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
@ -70,7 +72,7 @@ public class AnnotationUtil {
private ServletContext servletContext;
public AnnotationUtil(final StandardContext context) {
public AnnotationProcessor(final StandardContext context) {
this.context = context;
servletContext = context.getServletContext();
classLoader = servletContext.getClassLoader();
@ -175,6 +177,7 @@ public class AnnotationUtil {
/**
* Iterate API annotation and build API Configuration
*
* @param apiAnno
* @return
* @throws Throwable
@ -204,6 +207,7 @@ public class AnnotationUtil {
/**
* Get Resources for each API
*
* @param resourceRootContext
* @param apiRootContext
* @param annotatedMethods
@ -221,8 +225,11 @@ public class AnnotationUtil {
APIResource resource = new APIResource();
resource.setUriTemplate(makeContextURLReady(apiRootContext + subCtx));
String serverIP = System.getProperty(SERVER_HOST);
String httpServerPort = System.getProperty(HTTP_PORT);
DTConfiguration deviceTypeConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig().getDTDeploymentConfiguration();
String serverIP = deviceTypeConfig.getDtHostAddress();
String httpServerPort = deviceTypeConfig.getDtHostPort();
resource.setUri(PROTOCOL_HTTP + "://" + serverIP + ":" + httpServerPort + makeContextURLReady(
resourceRootContext) + makeContextURLReady(subCtx));
@ -266,6 +273,7 @@ public class AnnotationUtil {
/**
* Read Method annotations indicating HTTP Methods
*
* @param resource
* @param annotation
*/
@ -289,6 +297,7 @@ public class AnnotationUtil {
/**
* Append '/' to the context and make it URL ready
*
* @param context
* @return
*/

@ -83,6 +83,7 @@
javax.xml.bind,
org.wso2.carbon.utils.*,
org.wso2.carbon.device.mgt.common.*,
io.swagger.annotations.*;resolution:=optional,
org.wso2.carbon.device.mgt.core.*,
org.bouncycastle.pkcs.jcajce
</Import-Package>
@ -166,6 +167,12 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -18,19 +18,42 @@
package org.wso2.carbon.certificate.mgt.core.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigInteger;
@ApiModel(value = "CertificateResponse", description = "This class carries all information related to certificates")
public class CertificateResponse {
@ApiModelProperty(name = "certificate", value = "The certificate in bytes", required = true)
byte[] certificate;
@ApiModelProperty(name = "serialNumber", value = "It is the unique ID that is used to identify a certificate", required = true)
String serialNumber;
@ApiModelProperty(name = "tenantId", value = "The ID of the tenant who adds the certificate", required = true)
int tenantId;
@ApiModelProperty(name = "commonName", value = "In mutual SSL the common name refers to the serial number of the Android device.", required = true)
String commonName;
@ApiModelProperty(name = "notAfter", value = "The expiration date of the certificate that is inherent to the certificate", required = true)
long notAfter;
@ApiModelProperty(name = "notBefore", value = "The date from when the certificate is valid", required = true)
long notBefore;
@ApiModelProperty(name = "certificateserial", value = "The serial number of the certificate", required = true)
BigInteger certificateserial;
@ApiModelProperty(name = "issuer", value = "The identity of the authority that signs the SSL certificate", required = true)
String issuer;
@ApiModelProperty(name = "subject", value = "The identity of the certificate", required = true)
String subject;
@ApiModelProperty(name = "certificateVersion", value = "The version of the certificate", required = true)
int certificateVersion;
public long getNotAfter() {

@ -207,6 +207,24 @@
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>

@ -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.device.mgt.jaxrs;
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
}
}

@ -1,34 +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 javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
/**
* Authentication related REST-API interface.
*/
@Api(value = "Authentication")
@Produces({ "application/json", "application/xml" })
@Consumes({ "application/json", "application/xml" })
public interface Authentication {
}

@ -18,15 +18,10 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.*;
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.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
import javax.ws.rs.*;
@ -36,8 +31,10 @@ import javax.ws.rs.core.Response;
/**
* All the certificate related tasks such as saving certificates, can be done through this endpoint.
*/
@Api(value = "Certificate", description = "certificate related tasks such as saving certificates")
@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 {
@ -56,8 +53,7 @@ public interface Certificate {
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",
response = MediaType.class)
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")
@ -83,7 +79,7 @@ public interface Certificate {
notes = "Get the client side SSL certificate details",
response = CertificateResponse.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@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")
})
@ -112,7 +108,7 @@ public interface Certificate {
+ "page therefore the details are paginated",
response = PaginationResult.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@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")

@ -18,13 +18,8 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@ -34,7 +29,9 @@ import javax.ws.rs.core.Response;
* General Tenant Configuration REST-API implementation.
* All end points support JSON, XMl with content negotiation.
*/
@Api(value = "Configuration", description = "General Tenant Configuration implementation")
@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" })
@ -46,10 +43,9 @@ public interface Configuration {
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "POST",
value = "Configuring general platform settings",
notes = "Configure the general platform settings using this REST API",
response = ResponsePayload.class)
notes = "Configure the general platform settings using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Tenant configuration saved successfully"),
@ApiResponse(code = 201, message = "Tenant configuration saved successfully"),
@ApiResponse(code = 500, message = "Error occurred while saving the tenant configuration")
})
Response saveTenantConfiguration(@ApiParam(name = "configuration", value = "The required properties to "
@ -76,10 +72,9 @@ public interface Configuration {
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "PUT",
value = "Updating General Platform Configurations",
notes = "Update the notification frequency using this REST API",
response = ResponsePayload.class)
notes = "Update the notification frequency using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Tenant configuration updated successfully"),
@ApiResponse(code = 201, message = "Tenant configuration updated successfully"),
@ApiResponse(code = 500, message = "Error occurred while updating the tenant configuration")
})
Response updateConfiguration(@ApiParam(name = "configuration", value = "The required properties to update"

@ -29,7 +29,8 @@ import javax.ws.rs.core.Response;
/**
* Device related operations such as get all the available devices, etc.
*/
@Api(value = "Devices")
@Path("/devices")
@Api(value = "Device", description = "Device related operations such as get all the available devices, etc.")
@SuppressWarnings("NonJaxWsWebServices")
public interface Device {
@ -40,6 +41,7 @@ public interface Device {
* @return Device List
*/
@GET
@Path("devices")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
@ -94,7 +96,7 @@ public interface Device {
*/
@GET
@Path("user/{user}")
Response getDevice(@PathParam("user") String user);
Response getDeviceOfUser(@PathParam("user") String user);
/**
* Fetch device count of a given user.
@ -104,7 +106,7 @@ public interface Device {
*/
@GET
@Path("user/{user}/count")
Response getDeviceCount(@PathParam("user") String user);
Response getDeviceCountOfUser(@PathParam("user") String user);
/**
* Get current device count
@ -117,7 +119,7 @@ public interface Device {
httpMethod = "GET",
value = "Getting the Device Count",
notes = "Get the number of devices that are registered with WSO2 EMM.",
response = Integer.class)
response = int.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Device count"),
@ApiResponse(code = 500, message = "Error occurred while fetching the device count")

@ -18,14 +18,9 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.*;
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.jaxrs.beans.UserCredentialWrapper;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@ -36,7 +31,8 @@ import javax.ws.rs.core.Response;
/**
* Device information related operations.
*/
@Api(value = "DeviceInfo")
@Path("/information")
@Api(value = "DeviceInformation", description = "Device information related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
public interface DeviceInformation {

@ -40,10 +40,11 @@ import javax.ws.rs.core.Response;
* DeviceNotification management REST-API implementation.
* All end points support JSON, XMl with content negotiation.
*/
@Api(value = "DeviceNotification")
@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" })
@Consumes({"application/json", "application/xml"})
public interface DeviceNotification {
@GET
@ -57,9 +58,10 @@ public interface DeviceNotification {
response = Notification.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of Notifications"),
@ApiResponse(code = 200, message = "List of Notifications", response = Notification.class,
responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the notification list")
})
})
Response getNotifications();
@GET
@ -74,12 +76,13 @@ public interface DeviceNotification {
response = Notification.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of Notifications"),
@ApiResponse(code = 200, message = "List of Notifications", response = Notification.class,
responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the notification list")
})
})
Response getNotificationsByStatus(@ApiParam(name = "status", value = "Provide the notification status as"
+ " the value for {status}", required = true)
@PathParam("status") Notification.Status status);
+ " the value for {status}", required = true)
@PathParam("status") Notification.Status status);
@PUT
@Path("{id}/{status}")
@ -89,17 +92,16 @@ public interface DeviceNotification {
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",
response = ResponsePayload.class)
+ "change from NEW to CHECKED. Update the device notification status using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Notification status updated successfully"),
@ApiResponse(code = 201, message = "Notification status updated successfully"),
@ApiResponse(code = 500, message = "Error occurred while updating notification status")
})
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);
})
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(
@ -107,12 +109,11 @@ public interface DeviceNotification {
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",
response = ResponsePayload.class)
notes = "Notify users on device operation failures and other information using this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "NNotification has added successfully"),
@ApiResponse(code = 201, message = "NNotification has added successfully"),
@ApiResponse(code = 500, message = "Error occurred while updating notification status")
})
})
Response addNotification(Notification notification);
}

@ -18,23 +18,20 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.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.device.mgt.common.PaginationResult;
import io.swagger.annotations.*;
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.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Device search related operations such as getting device information.
*/
@Api(value = "DeviceSearch")
@Path("/search")
@Api(value = "DeviceSearch", description = "Device searching related operations can be found here.")
@SuppressWarnings("NonJaxWsWebServices")
public interface DeviceSearch {
@ -47,9 +44,9 @@ public interface DeviceSearch {
response = DeviceWrapper.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 200, message = "OK", response = DeviceWrapper.class, responseContainer = "List"),
@ApiResponse(code = 500, message = "Error occurred while searching the device information")
})
Response getDeviceInfo(@ApiParam(name = "enrollmentCertificates", value = "List of search conditions",
Response getFilteredDeviceInfo(@ApiParam(name = "enrollmentCertificates", value = "List of search conditions",
required = true) SearchContext searchContext);
}

@ -31,8 +31,10 @@ import javax.ws.rs.core.Response;
/**
* Features
*/
@Api(value = "Feature")
@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 {

@ -35,10 +35,8 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.List;
/**
*
*/
@Api(value = "Group")
@Path("/groups")
@Api(value = "Group", description = "Group related operations such as get all the available groups, etc.")
@SuppressWarnings("NonJaxWsWebServices")
public interface Group {
@ -59,7 +57,7 @@ public interface Group {
@GET
@Produces("application/json")
Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length);
Response getGroups(@QueryParam("start") int startIndex, @QueryParam("length") int length);
@Path("/all")
@GET
@ -119,8 +117,7 @@ public interface Group {
@PUT
@Produces("application/json")
Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("roleName") String roleName,
@FormParam("permissions") String[] permissions);
@PathParam("owner") String owner, @PathParam("roleName") String roleName, String[] permissions);
@DELETE
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")

@ -28,6 +28,7 @@ import javax.ws.rs.core.Response;
* This class represents license related operations.
*/
@Api(value = "License")
@Path("/license")
@SuppressWarnings("NonJaxWsWebServices")
public interface License {

@ -19,24 +19,20 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.*;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
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.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
*/
@Api(value = "Operation")
@Path("/operations")
@Api(value = "Operation", description = "Operation management related operations can be found here.")
public interface Operation {
/* @deprecated */
@ -49,7 +45,7 @@ public interface Operation {
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting Pagination Details for Operations on a Device.",
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." +
@ -57,23 +53,23 @@ public interface Operation {
"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.") })
@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.")})
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,
"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,
required = true) @PathParam("id") String id,
@ApiParam(name = "start", value = "Provide the starting pagination index. Example 10",
required = true) @QueryParam("start") int startIdx,
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,
" 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
@ -86,14 +82,14 @@ public interface Operation {
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.") })
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);
@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.")})
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
@ -109,14 +105,14 @@ public interface Operation {
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."),
@ApiResponse(code = 500, message = "Error occurred while fetching the apps of the device" +
".") })
@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" +
".")})
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,
"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);
required = true) @PathParam("id") String id);
@POST
@Path("installApp/{tenantDomain}")
@ -126,16 +122,16 @@ public interface Operation {
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.") })
@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,
" 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);
"{tenantDomain}. The default tenant domain " +
"of WSO2 EMM is carbon.super.",
required = true) @PathParam("tenantDomain") String tenantDomain);
@POST
@Path("uninstallApp/{tenantDomain}")
@ -145,14 +141,29 @@ public interface Operation {
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.") })
@ApiResponses(value = {@ApiResponse(code = 200, message = "Operation was successfully added to the queue."),
@ApiResponse(code = 500, message = "Error occurred while saving the operation.")})
Response uninstallApplication(@ApiParam(name = "applicationWrapper", value = "Details about the application and" +
" the users and roles it should be " +
"uninstalled.",
required = true) ApplicationWrapper applicationWrapper,
" 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);
"{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 = "POST",
value = "Retrieving the operation details.",
notes = "This will return the operation details including the responses from the devices")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Activity details provided successfully.."),
@ApiResponse(code = 500, message = "Error occurred while fetching the activity for the supplied id.")})
Response getActivity(@ApiParam(name = "id", value = "Provide activity id {id} as ACTIVITY_(number)",
required = true) @PathParam("id") String id)
throws MDMAPIException;
}

@ -20,25 +20,16 @@ package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.*;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
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.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
*
*/
@Api(value = "Policy")
@Path("/policies")
@Api(value = "Policy", description = "Policy management related operations can be found here.")
public interface Policy {
@POST
@ -51,11 +42,11 @@ public interface 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") })
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created the policy."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"adding the policy")})
Response addPolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.",
required = true) PolicyWrapper policyWrapper);
required = true) PolicyWrapper policyWrapper);
@POST
@Path("active-policy")
@ -68,14 +59,14 @@ public interface Policy {
"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") })
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created the policy."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"adding the policy")})
Response addActivePolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.",
required = true) PolicyWrapper policyWrapper);
required = true) PolicyWrapper policyWrapper);
@GET
@Produces({ MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
@ -84,9 +75,10 @@ public interface Policy {
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."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"fetching the policies.") })
@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.")})
Response getAllPolicies();
@GET
@ -97,12 +89,13 @@ public interface Policy {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of a Policy.",
notes = "Retrieve the details of a selected policy in WSO2 EMM.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Fetched policy details."),
@ApiResponse(code = 500, message = "Policy Management related error occurred when " +
"fetching the policies.") })
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.")})
Response getPolicy(@ApiParam(name = "id", value = "Policy ID value to identify a policy uniquely.",
required = true) @PathParam("id") int policyId);
required = true) @PathParam("id") int policyId);
@GET
@Path("count")
@ -112,9 +105,9 @@ public interface Policy {
httpMethod = "GET",
value = "Getting the Policy Count.",
notes = "Get the number of policies that are created in WSO2 EMM.",
response = Integer.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Fetched the policy count."),
@ApiResponse(code = 500, message = "Error while Fetching the policy count.") })
response = int.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched the policy count."),
@ApiResponse(code = 500, message = "Error while Fetching the policy count.")})
Response getPolicyCount();
@PUT
@ -126,13 +119,13 @@ public interface Policy {
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") })
@ApiResponses(value = {@ApiResponse(code = 201, message = "Policy has been updated successfully."),
@ApiResponse(code = 500, message = "Policy Management related exception in policy " +
"update")})
Response updatePolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.",
required = true) PolicyWrapper policyWrapper,
required = true) PolicyWrapper policyWrapper,
@ApiParam(name = "id", value = "Policy ID value to identify a policy uniquely.",
required = true) @PathParam("id") int policyId);
required = true) @PathParam("id") int policyId);
@PUT
@Path("priorities")
@ -145,12 +138,12 @@ public interface Policy {
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.") })
@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.")})
Response updatePolicyPriorities(@ApiParam(name = "priorityUpdatedPolicies",
value = "List of policy update details..",
required = true) List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies);
value = "List of policy update details..",
required = true) List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies);
@POST
@Path("bulk-remove")
@ -162,11 +155,11 @@ public interface Policy {
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.") })
@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.")})
Response bulkRemovePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be deleted.",
required = true) List<Integer> policyIds);
required = true) List<Integer> policyIds);
@PUT
@Produces("application/json")
@ -178,10 +171,10 @@ public interface Policy {
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.") })
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully activated."),
@ApiResponse(code = 500, message = "Error in activating policies.")})
Response activatePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be activated.",
required = true) List<Integer> policyIds);
required = true) List<Integer> policyIds);
@PUT
@Produces("application/json")
@ -193,10 +186,10 @@ public interface Policy {
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.") })
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully deactivated."),
@ApiResponse(code = 500, message = "Error in deactivating policies.")})
Response inactivatePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be deactivated.",
required = true) List<Integer> policyIds) throws MDMAPIException;
required = true) List<Integer> policyIds) throws MDMAPIException;
@PUT
@Produces("application/json")
@ -211,8 +204,8 @@ public interface Policy {
" 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.") })
@ApiResponses(value = {@ApiResponse(code = 200, message = "Changes have been successfully updated."),
@ApiResponse(code = 500, message = "Error in updating policies.")})
Response applyChanges();
@GET
@ -227,11 +220,11 @@ public interface 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.") })
@ApiResponses(value = {@ApiResponse(code = 200, message = "Policy monitoring service started successfully."),
@ApiResponse(code = 500, message = "Policy Management related exception when starting " +
"monitoring service.")})
Response startTaskService(@ApiParam(name = "milliseconds", value = "Policy monitoring frequency in milliseconds.",
required = true) @PathParam("milliseconds") int monitoringFrequency);
required = true) @PathParam("milliseconds") int monitoringFrequency);
@GET
@Path("update-task/{milliseconds}")
@ -254,12 +247,13 @@ public interface Policy {
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.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Fetched current policy."),
@ApiResponse(code = 500, message = "Error occurred while getting the current policy.") })
" 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,
" 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);
required = true) @PathParam("id") String id);
}

@ -30,6 +30,7 @@ import javax.ws.rs.core.Response;
* These end points provide profile related operations.
*/
@Api(value = "Profile")
@Path("/profiles")
@SuppressWarnings("NonJaxWsWebServices")
public interface Profile {

@ -19,27 +19,16 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
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.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
*
*/
@Api(value = "Role")
@Path("/roles")
@Api(value = "Role", description = "Role management related operations can be found here.")
public interface Role {
@GET
@ -54,7 +43,7 @@ public interface Role {
response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of available roles"),
@ApiResponse(code = 500, message = "Error occurred while fetching the role list.") })
Response getRoles();
Response getAllRoles();
@GET
@Path("{userStore}")
@ -69,7 +58,7 @@ public interface Role {
response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of available roles"),
@ApiResponse(code = 500, message = "Error occurred while fetching the role list.") })
Response getRoles(@ApiParam(name = "userStore", value = "Provide the name of the UserStore you wish to get the" +
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);
@ -203,9 +192,10 @@ public interface Role {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the Role Count.",
response = Integer.class,
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.") })
Response getRoleCount();
}

@ -18,25 +18,12 @@
package org.wso2.carbon.device.mgt.jaxrs.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.*;
import org.apache.axis2.databinding.types.soapencoding.Integer;
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 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.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@ -44,7 +31,8 @@ import java.util.List;
/**
* This represents the JAX-RS services of User related functionality.
*/
@Api(value = "User")
@Path("/users")
@Api(value = "User", description = "User management related operations can be found here.")
public interface User {
@POST
@ -112,8 +100,7 @@ public interface User {
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",
response = ResponsePayload.class)
+ "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"),
@ -139,7 +126,7 @@ public interface User {
@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'")
})
Response getRoles(@ApiParam(name = "username", value = "Provide the user name of the user you wish to get"
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
@ -150,7 +137,8 @@ public interface User {
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 = ResponsePayload.class)
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")
@ -253,7 +241,7 @@ public interface User {
httpMethod = "GET",
value = "Getting the User Count",
notes = "Get the number of users in WSO2 EMM",
response = Integer.class)
response = int.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 500, message = "Error occurred while retrieving the list of users that exist"
@ -264,7 +252,7 @@ public interface User {
@PUT
@Path("{roleName}/users")
@Produces({MediaType.APPLICATION_JSON})
Response updateRoles(@PathParam("username") String username, List<String> userList);
Response updateRoles(@PathParam("roleName") String roleName, List<String> userList);
@POST
@Path("change-password")
@ -275,10 +263,9 @@ public interface User {
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",
response = UserCredentialWrapper.class)
notes = "A user is able to change the password to secure their EMM profile via this REST API")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "UserImpl password by username: 'Username' was "
@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"
@ -301,10 +288,9 @@ public interface User {
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.",
response = UserCredentialWrapper.class)
+ "not aware of the new password.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "UserImpl password by username: 'Username' was "
@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"

@ -1,36 +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 javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
/**
* Authentication related REST-API implementation.
*/
@Produces({ "application/json", "application/xml" })
@Consumes({ "application/json", "application/xml" })
public class AuthenticationImpl {
private static Log log = LogFactory.getLog(AuthenticationImpl.class);
}

@ -142,7 +142,7 @@ public class DeviceImpl implements Device{
*/
@GET
@Path("user/{user}")
public Response getDevice(@PathParam("user") String user) {
public Response getDeviceOfUser(@PathParam("user") String user) {
List<org.wso2.carbon.device.mgt.common.Device> devices;
try {
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user);
@ -165,7 +165,7 @@ public class DeviceImpl implements Device{
*/
@GET
@Path("user/{user}/count")
public Response getDeviceCount(@PathParam("user") String user) {
public Response getDeviceCountOfUser(@PathParam("user") String user) {
try {
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user);
return Response.status(Response.Status.OK).entity(count).build();

@ -38,7 +38,7 @@ public class DeviceSearchImpl implements DeviceSearch {
private static Log log = LogFactory.getLog(DeviceSearchImpl.class);
@GET
public Response getDeviceInfo(SearchContext searchContext) {
public Response getFilteredDeviceInfo(SearchContext searchContext) {
SearchManagerService searchManagerService;
List<DeviceWrapper> devices;
try {

@ -103,7 +103,7 @@ public class OperationImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Opera
@Override
@GET
@Path("{type}/{id}")
public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String 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();
@ -224,4 +224,22 @@ public class OperationImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Opera
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 {
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation;
DeviceManagementProviderService dmService;
try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operation = 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(operation).build();
}
}

@ -65,7 +65,7 @@ public class RoleImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Role {
@Override
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getRoles() {
public Response getAllRoles() {
List<String> filteredRoles;
try {
filteredRoles = getRolesFromUserStore();
@ -89,7 +89,7 @@ public class RoleImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Role {
@GET
@Path("{userStore}")
@Produces({MediaType.APPLICATION_JSON})
public Response getRoles(@PathParam("userStore") String userStore) {
public Response getRolesOfUserStore(@PathParam("userStore") String userStore) {
String[] roles;
try {
AbstractUserStoreManager abstractUserStoreManager =
@ -438,10 +438,10 @@ public class RoleImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Role {
String msg = "Error occurred while retrieving the list of user roles.";
throw new MDMAPIException(msg, e);
}
// removing all internal roles and roles created for Service-providers
// 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/"))) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith("Application/"))) {
filteredRoles.add(role);
}
}

@ -371,7 +371,7 @@ public class UserImpl implements org.wso2.carbon.device.mgt.jaxrs.api.User {
@GET
@Path("roles")
@Produces({MediaType.APPLICATION_JSON})
public Response getRoles(@QueryParam("username") String username) {
public Response getRolesOfUser(@QueryParam("username") String username) {
ResponsePayload responsePayload = new ResponsePayload();
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
@ -716,7 +716,7 @@ public class UserImpl implements org.wso2.carbon.device.mgt.jaxrs.api.User {
@PUT
@Path("{roleName}/users")
@Produces({MediaType.APPLICATION_JSON})
public Response updateRoles(@PathParam("username") String username, List<String> userList) {
public Response updateRoles(@PathParam("roleName") String username, List<String> userList) {
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {

@ -18,45 +18,57 @@
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.DeviceIdentifier;
import java.util.List;
@ApiModel(value = "ApplicationWrapper", description = "Application details together with user, " +
"role or devices the application is associated with.")
public class ApplicationWrapper {
private List<String> userNameList;
private List<String> roleNameList;
private List<DeviceIdentifier> deviceIdentifiers;
private MobileApp application;
public MobileApp getApplication() {
return application;
}
public void setApplication(MobileApp application) {
this.application = application;
}
public List<String> getUserNameList() {
return userNameList;
}
public void setUserNameList(List<String> userNameList) {
this.userNameList = userNameList;
}
public List<String> getRoleNameList() {
return roleNameList;
}
public void setRoleNameList(List<String> roleNameList) {
this.roleNameList = roleNameList;
}
public List<DeviceIdentifier> getDeviceIdentifiers() {
return deviceIdentifiers;
}
public void setDeviceIdentifiers(List<DeviceIdentifier> deviceIdentifiers) {
this.deviceIdentifiers = deviceIdentifiers;
}
@ApiModelProperty(name = "userNameList", value = "List of user names.", required = true)
private List<String> userNameList;
@ApiModelProperty(name = "roleNameList", value = "List of role names.", required = true)
private List<String> roleNameList;
@ApiModelProperty(name = "deviceIdentifiers", value = "List of device identifiers.", required = true,
dataType = "List[org.wso2.carbon.device.mgt.common.DeviceIdentifier]")
private List<DeviceIdentifier> deviceIdentifiers;
@ApiModelProperty(name = "application", value = "Details of the mobile application.", required = true)
private MobileApp application;
public MobileApp getApplication() {
return application;
}
public void setApplication(MobileApp application) {
this.application = application;
}
public List<String> getUserNameList() {
return userNameList;
}
public void setUserNameList(List<String> userNameList) {
this.userNameList = userNameList;
}
public List<String> getRoleNameList() {
return roleNameList;
}
public void setRoleNameList(List<String> roleNameList) {
this.roleNameList = roleNameList;
}
public List<DeviceIdentifier> getDeviceIdentifiers() {
return deviceIdentifiers;
}
public void setDeviceIdentifiers(List<DeviceIdentifier> deviceIdentifiers) {
this.deviceIdentifiers = deviceIdentifiers;
}
}

@ -18,9 +18,19 @@
package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "EnrollmentCertificate", description = "Details of certificates used in enrollment.")
public class EnrollmentCertificate {
@ApiModelProperty(name = "serial", value = "The unique ID used to identify a certificate. This is the devices " +
"serial number in case of mutual SSL is used for enrollment.",
required = true )
String serial;
@ApiModelProperty(name = "pem", value = "Case 64 encode .pem file content.", required = true )
String pem;
@ApiModelProperty(name = "tenantId", value = "The ID of the tenant who adds the certificate.", required = true )
int tenantId;
public int getTenantId() {

@ -18,24 +18,51 @@
package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Properties;
/**
* This class represents the generic mobile AuthenticationImpl information
* which is used by AppM.
*/
@ApiModel(value = "MobileApp", description = "Details of a mobile application.")
public class MobileApp {
@ApiModelProperty(name = "id", value = "Id of the app used internally.", required = true)
private String id;
@ApiModelProperty(name = "name", value = "The name of the application.", required = true)
private String name;
@ApiModelProperty(name = "type", value = "The type of the application. The following types of applications are " +
"supported: enterprise, public and webapp..", required = true)
private MobileAppTypes type;
@ApiModelProperty(name = "platform", value = "Platform the app can be installed on .", required = true)
private String platform;
@ApiModelProperty(name = "version", value = "Version of the application.", required = true)
private String version;
@ApiModelProperty(name = "identifier", value = "The package name of the application.", required = true)
private String identifier;
@ApiModelProperty(name = "iconImage", value = "Link to the icon of the app.", required = true)
private String iconImage;
@ApiModelProperty(name = "packageName", value = "Define the exact name of the application package. You can use one " +
"of the following methods to get the package name.\n" +
"Go to the respective application in the play store and copy the" +
" ID or package name from the URL.\n" +
"Example: The play store application URL for the Viber app is " +
"https://play.google.com/store/apps/details?id=com.viber.voip&hl=en." +
" Therefore, the package name or " +
"the application ID is: id=com.viber.voip \n" +
"Download the System Info for Android to your device from the" +
" play store. \n" +
"Once the application is successfully installed go to the Tasks " +
"tab and you will see the package name under the respective " +
"application..", required = true)
private String packageName;
@ApiModelProperty(name = "appIdentifier", value = "The package name of the application.", required = true)
private String appIdentifier;
private String location;
@ApiModelProperty(name = "properties", value = "List of meta data.", required = true)
private Properties properties;
public MobileAppTypes getType() {

@ -18,21 +18,52 @@
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 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"
+ "Warning - If the device does not adhere to the given policies a warning message will be sent\n"
+ "Monitor - If the device does not adhere to the given policies the server is notified of the "
+ "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"
+ "BYOD (Bring Your Own Device) - The policy will only be applied on the BYOD device type\n"
+ "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",
required = true)
private List<Device> devices;
@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() {

@ -18,9 +18,17 @@
package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "PriorityUpdatedPolicyWrapper", description = "This class carries all information related "
+ "to Priority Updated Policy Wrapper ")
public class PriorityUpdatedPolicyWrapper {
@ApiModelProperty(name = "id", value = "Define the ID of the policy", required = true)
private int id;
@ApiModelProperty(name = "priority", value = "Define the priority of the order, where 1 indicates the "
+ "highest priority", required = true)
private int priority;
public int getId() {

@ -18,23 +18,36 @@
package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.sql.Timestamp;
import java.util.List;
@XmlRootElement
@ApiModel(value = "Profile", description = "This class carries all information related to policy profiles")
public class Profile {
@ApiModelProperty(name = "profileId", value = "The ID of each profile that is in the selected policy",
required = true)
private int profileId;
@ApiModelProperty(name = "profileName", value = "The name of the profile", required = true)
private String profileName;
@ApiModelProperty(name = "tenantId", value = "The ID of the tenant that added the policy", required = true)
private int tenantId;
@ApiModelProperty(name = "deviceType", value = "Contains the device type details the policy was created "
+ "for", required = true)
private DeviceType deviceType;
@ApiModelProperty(name = "createdDate", value = "The date the policy was created", required = true)
private Timestamp createdDate;
@ApiModelProperty(name = "updatedDate", value = "The date the changes made to the policy was published to"
+ " the devices registered with the EMM", required = true)
private Timestamp updatedDate;
@ApiModelProperty(name = "profileFeaturesList", value = "Contains the features specific to each profile "
+ "in the policy", required = true)
private List<ProfileFeature> profileFeaturesList; // Features included in the policies.
public DeviceType getDeviceType() {
@ -104,4 +117,5 @@ public class Profile {
public void setProfileFeaturesList(List<ProfileFeature> profileFeaturesList) {
this.profileFeaturesList = profileFeaturesList;
}
}

@ -19,15 +19,30 @@
package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.google.gson.Gson;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(value = "ProfileFeature", description = "This class carries all information related to profile "
+ "features")
public class ProfileFeature implements Serializable {
@ApiModelProperty(name = "id", value = "Define the ID", required = true)
private int id;
@ApiModelProperty(name = "featureCode", value = "Provide the code that defines the policy you wish to add",
required = true)
private String featureCode;
@ApiModelProperty(name = "profileId", value = "Define the ID of the profile", required = true)
private int profileId;
@ApiModelProperty(name = "deviceTypeId", value = "The ID used to define the type of the device platform",
required = true)
private int deviceTypeId;
@ApiModelProperty(name = "content", value = "The list of parameters that define the policy",
required = true)
private Object content;
@ApiModelProperty(name = "payLoad", value = "The payload which is submitted to each feature",
required = true)
private String payLoad;
public int getId() {

@ -23,54 +23,54 @@ import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@ApiModel(value = "RoleWrapper", description = "Role details including permission and the users in the roles are " +
"wrapped here.")
"wrapped here.")
public class RoleWrapper {
@ApiModelProperty(name = "roleName", value = "The name of the role.", required = true)
private String roleName;
private String roleName;
@ApiModelProperty(name = "permissions", value = "Lists out all the permissions associated with roles.",
required = true)
private String[] permissions;
required = true, dataType = "List[java.lang.String]")
private String[] permissions;
@ApiModelProperty(name = "users", value = "The list of users assigned to the selected role.",
required = true)
private String[] users;
required = true, dataType = "List[java.lang.String]")
private String[] users;
@ApiModelProperty(name = "permissionList", value = "This contain the following, " +
"\n resourcePath\tThe path related to the API.\n " +
"displayName\tThe name of the permission that is shown " +
"in the UI.\n" +
"nodeList\tLists out the nested permissions.",
required = true)
private UIPermissionNode permissionList;
"\n resourcePath\tThe path related to the API.\n " +
"displayName\tThe name of the permission that is shown " +
"in the UI.\n" +
"nodeList\tLists out the nested permissions.",
required = true)
private UIPermissionNode permissionList;
public String getRoleName() {
return roleName;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String[] getPermissions() {
return permissions;
}
public String[] getPermissions() {
return permissions;
}
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
public String[] getUsers() {
return users;
}
public String[] getUsers() {
return users;
}
public void setUsers(String[] users) {
this.users = users;
}
public void setUsers(String[] users) {
this.users = users;
}
public UIPermissionNode getPermissionList() {
return permissionList;
}
public UIPermissionNode getPermissionList() {
return permissionList;
}
public void setPermissionList(UIPermissionNode permissionList) {
this.permissionList = permissionList;
}
public void setPermissionList(UIPermissionNode permissionList) {
this.permissionList = permissionList;
}
}

@ -18,13 +18,20 @@
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 {
@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() {

@ -18,16 +18,26 @@
package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "UserWrapper", description = "User details and the roles of the user.")
public class UserWrapper {
private String username;
/*
Base64 encoded password
*/
@ApiModelProperty(name = "password", value = "Base64 encoded password.", required = true )
private String password;
@ApiModelProperty(name = "firstname", value = "The first name of the user.", required = true )
private String firstname;
@ApiModelProperty(name = "lastname", value = "The last name of the user.", required = true )
private String lastname;
@ApiModelProperty(name = "emailAddress", value = "The email address of the user.", required = true )
private String emailAddress;
@ApiModelProperty(name = "roles", value = "List of roles.", required = true )
private String[] roles;
public String getUsername() {

@ -24,145 +24,46 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="operationService" address="/operations">
<jaxrs:server id="services" address="/">
<jaxrs:serviceBeans>
<ref bean="operationServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="featureService" address="/features">
<jaxrs:serviceBeans>
<ref bean="featureServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="deviceService" address="/devices">
<jaxrs:serviceBeans>
<ref bean="deviceServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="deviceGroupService" address="/groups">
<jaxrs:serviceBeans>
<ref bean="groupServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="userService" address="/users">
<jaxrs:serviceBeans>
<ref bean="userServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="roleService" address="/roles">
<jaxrs:serviceBeans>
<ref bean="roleServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="policyService" address="/policies">
<jaxrs:serviceBeans>
<ref bean="policyServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="profileService" address="/profiles">
<jaxrs:serviceBeans>
<ref bean="profileServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="configurationService" address="/configuration">
<jaxrs:serviceBeans>
<ref bean="configurationServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="licenseService" address="/license">
<jaxrs:serviceBeans>
<ref bean="licenseServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</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>
<jaxrs:server id="notificationService" address="/notifications">
<jaxrs:serviceBeans>
<ref bean="notificationServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="informationService" address="/information">
<jaxrs:serviceBeans>
<ref bean="informationServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="searchService" address="/search">
<jaxrs:serviceBeans>
<ref bean="searchingServiceBean"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
<ref bean="swaggerWriter"/>
</jaxrs:providers>
</jaxrs:server>
<!--
<jaxrs:server id="authenticationService" address="/authentication">
<jaxrs:serviceBeans>
<ref bean="authenticationServiceBean"/>
</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" />
<bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig">
<property name="resourcePackage" value="org.wso2.carbon.device.mgt.jaxrs"/>
<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="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="operationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.OperationImpl"/>
<bean id="deviceServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceImpl"/>
<bean id="groupServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.GroupImpl"/>
@ -175,9 +76,6 @@
<bean id="certificateServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.CertificateImpl"/>
<bean id="informationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceInformationImpl"/>
<bean id="searchingServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceSearchImpl"/>
<!--
<bean id="authenticationServiceBean" class="AuthenticationImpl"/>
-->
<bean id="policyServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.PolicyImpl"/>
<bean id="profileServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.ProfileImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>

@ -25,6 +25,16 @@
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<!--<init-param>-->
<!--<param-name>swagger.api.basepath</param-name>-->
<!--<param-value>http://localhost:9763/test</param-value>-->
<!--</init-param>-->
<!-- configure a security filter -->
<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>
@ -71,4 +81,13 @@
</user-data-constraint>
</security-constraint>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>org.wso2.carbon.device.mgt.jaxrs.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

@ -49,7 +49,8 @@
org.wso2.carbon.device.mgt.common.*
</Export-Package>
<Import-Package>
*;resolution:=optional,
javax.xml.bind.annotation,
io.swagger.annotations.*;resolution:=optional
</Import-Package>
</instructions>
</configuration>

@ -24,35 +24,36 @@ import java.io.Serializable;
import java.util.List;
@ApiModel(value = "Device", description = "This class carries all information related to a managed device.")
public class Device implements Serializable{
public class Device implements Serializable {
private static final long serialVersionUID = 1998101711L;
private static final long serialVersionUID = 1998101711L;
@ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.",
required = true)
private int id;
required = true)
private int id;
@ApiModelProperty(name = "name", value = "The device name that can be set on the device by the device user.",
required = true)
required = true)
private String name;
@ApiModelProperty(name = "type", value = "The OS type of the device.", required = true)
private String type;
private String type;
@ApiModelProperty(name = "description", value = "Additional information on the device.", required = true)
private String description;
private String description;
@ApiModelProperty(name = "deviceIdentifier", value = "This is a 64-bit number (as a hex string) that is randomly" +
" generated when the user first sets up the device and should" +
" remain constant for the lifetime of the user's device." +
" The value may change if a factory reset is performed on " +
"the device.",
required = true)
private String deviceIdentifier;
" generated when the user first sets up the device and should" +
" remain constant for the lifetime of the user's device." +
" The value may change if a factory reset is performed on " +
"the device.",
required = true)
private String deviceIdentifier;
@ApiModelProperty(name = "enrolmentInfo", value = "This defines the device registration related information. " +
"It is mandatory to define this information.", required = true)
"It is mandatory to define this information.", required = true)
private EnrolmentInfo enrolmentInfo;
@ApiModelProperty(name = "features", value = "List of features.", required = true)
private List<Feature> features;
private List<Device.Property> properties;
public Device() {}
public Device() {
}
public Device(String name, String type, String description, String deviceId, EnrolmentInfo enrolmentInfo,
List<Feature> features, List<Property> properties) {
@ -65,13 +66,13 @@ public class Device implements Serializable{
this.properties = properties;
}
public int getId() {
return id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
@ -89,21 +90,21 @@ public class Device implements Serializable{
this.type = type;
}
public String getDescription() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public EnrolmentInfo getEnrolmentInfo() {
return enrolmentInfo;
@ -113,43 +114,43 @@ public class Device implements Serializable{
this.enrolmentInfo = enrolmentInfo;
}
public List<Feature> getFeatures() {
return features;
}
public List<Feature> getFeatures() {
return features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
public List<Device.Property> getProperties() {
return properties;
}
public List<Device.Property> getProperties() {
return properties;
}
public void setProperties(List<Device.Property> properties) {
this.properties = properties;
}
public void setProperties(List<Device.Property> properties) {
this.properties = properties;
}
public static class Property {
public static class Property {
private String name;
private String value;
private String name;
private String value;
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public void setValue(String value) {
this.value = value;
}
}
@Override
public String toString() {
@ -166,22 +167,22 @@ public class Device implements Serializable{
"]";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Device))
return false;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Device))
return false;
Device device = (Device) o;
Device device = (Device) o;
return getDeviceIdentifier().equals(device.getDeviceIdentifier());
return getDeviceIdentifier().equals(device.getDeviceIdentifier());
}
}
@Override
public int hashCode() {
return getDeviceIdentifier().hashCode();
}
@Override
public int hashCode() {
return getDeviceIdentifier().hashCode();
}
}

@ -39,8 +39,7 @@ public class Feature implements Serializable {
"Features allow you to perform operations on any device type, " +
"such as android, iOS or windows..", required = true )
private String deviceType;
private String method;
private String type;
@ApiModelProperty(name = "metadataEntries", value = "Properties related to features.", required = true )
private List<MetadataEntry> metadataEntries;
@ -97,24 +96,6 @@ public class Feature implements Serializable {
this.description = description;
}
@XmlElement
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@XmlElement
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public static class MetadataEntry implements Serializable {
private int id;

@ -18,18 +18,30 @@
package org.wso2.carbon.device.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
/**
* This class holds necessary data to represent a paginated result.
*/
@ApiModel(value = "PaginationResult", description = "This class carries all information related Pagination Result")
public class PaginationResult implements Serializable {
private static final long serialVersionUID = 1998101711L;
@ApiModelProperty(name = "recordsTotal", value = "The total number of records that are given before filtering", required = true)
private int recordsTotal;
@ApiModelProperty(name = "recordsFiltered", value = "The total number of records that are given after filtering", required = true)
private int recordsFiltered;
@ApiModelProperty(name = "draw", value = "The draw counter that this object is a response to, from the draw parameter sent as part of the data request", required = true)
private int draw;
@ApiModelProperty(name = "data", value = "The details of the SSL certificate", required = true)
private List<?> data;
public int getRecordsTotal() {

@ -18,26 +18,41 @@
*/
package org.wso2.carbon.device.mgt.common.app.mgt;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Properties;
@ApiModel(value = "Application", description = "This class carries all information related application")
public class Application implements Serializable {
private static final long serialVersionUID = 1998101711L;
@ApiModelProperty(name = "id", value = "The ID given to the application when it is stored in the EMM database", required = true)
private int id;
@ApiModelProperty(name = "platform", value = "The mobile device platform. It can be android, ios or windows", required = true)
private String platform;
@ApiModelProperty(name = "category", value = "The application category", required = true)
private String category;
@ApiModelProperty(name = "name", value = "The application's name", required = true)
private String name;
private String locationUrl;
@ApiModelProperty(name = "imageUrl", value = "The icon url of the application", required = true)
private String imageUrl;
@ApiModelProperty(name = "version", value = "The application's version", required = true)
private String version;
@ApiModelProperty(name = "type", value = "The application type", required = true)
private String type;
@ApiModelProperty(name = "appProperties", value = "The properties of the application", required = true)
private Properties appProperties;
@ApiModelProperty(name = "applicationIdentifier", value = "The application identifier", required = true)
private String applicationIdentifier;
@ApiModelProperty(name = "memoryUsage", value = "AMount of memory used by the application", required = true)
private int memoryUsage;
public String getType() {
return type;
}

@ -25,13 +25,13 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ApiModel(value = "DeviceWrapper", description = "This contains device details including, " +
"location and device meta information.")
"location and device meta information.")
public class DeviceWrapper {
@ApiModelProperty(name = "device", value = "Device's basic information", required = true)
private Device device;
@ApiModelProperty(name = "deviceIdentifier", value = "Device identifier used to identify a device.",
required = true)
required = true)
private DeviceIdentifier deviceIdentifier;
@ApiModelProperty(name = "deviceInfo", value = "Device's runtime information", required = true)
private DeviceInfo deviceInfo;

@ -18,11 +18,15 @@
package org.wso2.carbon.device.mgt.common.notification.mgt;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
/**
* DTO of Notification object which is used to communicate Operation notifications to MDM core.
*/
@ApiModel(value = "Notification", description = "This is used to communicate Operation notifications to MDM.")
public class Notification {
public enum Status{
@ -33,10 +37,20 @@ public class Notification {
ALERT,
}
@ApiModelProperty(name = "notificationId", value = "Defines the notification ID.", required = true )
private int notificationId;
@ApiModelProperty(name = "deviceIdentifier", value = "Defines the device identification properties.",
required = true )
private DeviceIdentifier deviceIdentifier;
@ApiModelProperty(name = "description", value = "Provides the message you want to send to the user.",
required = true )
private String description;
@ApiModelProperty(name = "operationId", value = "Provides the operationID.", required = true )
private int operationId;
@ApiModelProperty(name = "status", value = "Provides the status of the message." +
"The following values can be assigned for the status.\n" +
"NEW: The message is in the unread state.\n" +
"CHECKED: The message is in the read state.", required = true )
private Status status;
public Status getStatus() {

@ -19,9 +19,17 @@
package org.wso2.carbon.device.mgt.common.operation.mgt;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "OperationResponse", description = "This class carries all information related to operation"
+ " responses")
public class OperationResponse {
@ApiModelProperty(name = "response", value = "Operation response return from the device", required = true)
private String response;
@ApiModelProperty(name = "recievedTimeStamp", value = "Time that the operation response received",
required = true)
private String recievedTimeStamp;
public String getResponse() {

@ -83,8 +83,7 @@
org.apache.catalina.core,
org.apache.commons.collections,
org.wso2.carbon.email.sender.*,
io.swagger.annotations.*,
*;resolution:=optional,
io.swagger.annotations.*;resolution:=optional,
org.wso2.carbon,
org.wso2.carbon.base
</Import-Package>
@ -247,6 +246,12 @@
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -28,6 +28,9 @@ public final class DeviceManagementConstants {
public static final String PROPERTY_SETUP = "setup";
public static final String DEFAULT_LICENSE_CONFIG_XML_NAME = "license-config.xml";
public static final String PROPERTY_PROFILE = "profile";
public static final String PROFILE_DT_WORKER = "dtWorker";
public static final String PROFILE_DEFAULT = "default";
}
public static final class AppManagement {

@ -17,6 +17,7 @@
*/
package org.wso2.carbon.device.mgt.core.config;
import org.wso2.carbon.device.mgt.core.config.deviceType.DTConfiguration;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration;
@ -37,6 +38,7 @@ public final class DeviceManagementConfig {
private IdentityConfigurations identityConfigurations;
private PolicyConfiguration policyConfiguration;
//private List<String> pushNotificationProviders;
private DTConfiguration dTDepyloymentConfiguration;
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
@ -75,6 +77,15 @@ public final class DeviceManagementConfig {
this.taskConfiguration = taskConfiguration;
}
@XmlElement(name = "DTDeploymentConfiguration", required = true)
public DTConfiguration getDTDeploymentConfiguration() {
return dTDepyloymentConfiguration;
}
public void setDTDeploymentConfiguration(DTConfiguration dTDeploymentConfiguration) {
this.dTDepyloymentConfiguration = dTDeploymentConfiguration;
}
// @XmlElementWrapper(name = "PushNotificationProviders", required = true)
// @XmlElement(name = "Provider", required = true)
// public List<String> getPushNotificationProviders() {

@ -0,0 +1,53 @@
/*
* 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.
*/
/**
* This class will read the configurations related to task. This task will be responsible for adding the operations.
*/
package org.wso2.carbon.device.mgt.core.config.deviceType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DTDepyloymentConfiguration")
public class DTConfiguration {
private String dtHostAddress;
private String dtHostPort;
@XmlElement(name = "DTHostAddress", required = true)
public String getDtHostAddress() {
return dtHostAddress;
}
public void setDtHostAddress(String dtHostAddress) {
this.dtHostAddress = dtHostAddress;
}
@XmlElement(name = "DTHostPort", required = true)
public String getDtHostPort() {
return dtHostPort;
}
public void setDtHostPort(String dtHostPort) {
this.dtHostPort = dtHostPort;
}
}

@ -18,12 +18,19 @@
package org.wso2.carbon.device.mgt.core.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(value = "DeviceType", description = "This class carries all information related device types")
public class DeviceType implements Serializable {
private static final long serialVersionUID = 7927802716452548282L;
@ApiModelProperty(name = "id", value = "Device type id", required = true)
private int id;
@ApiModelProperty(name = "name", value = "Device type name", required = true)
private String name;
public DeviceType() {

@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
@ -36,6 +37,7 @@ import java.util.HashMap;
public class DeviceManagementDataHolder {
private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder();
private RealmService realmService;
private TenantManager tenantManager;
private DeviceManagementProviderService deviceManagerProvider;
@ -49,12 +51,8 @@ public class DeviceManagementDataHolder {
private HashMap<String,Boolean> requireDeviceAuthorization = new HashMap<>();
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private GroupManagementProviderService groupManagementProviderService;
private TaskService taskService;
//private EmailSenderService emailSenderService;
private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder();
private EmailSenderService emailSenderService;
private DeviceManagementDataHolder() {}
@ -74,6 +72,10 @@ public class DeviceManagementDataHolder {
this.setTenantManager(realmService);
}
public TenantManager getTenantManager() {
return tenantManager;
}
private void setTenantManager(RealmService realmService) {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
@ -81,10 +83,6 @@ public class DeviceManagementDataHolder {
this.tenantManager = realmService.getTenantManager();
}
public TenantManager getTenantManager() {
return tenantManager;
}
public DeviceManagementProviderService getDeviceManagementProvider() {
return deviceManagerProvider;
}
@ -189,13 +187,13 @@ public class DeviceManagementDataHolder {
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
//
// public EmailSenderService getEmailSenderService() {
// return emailSenderService;
// }
//
// public void setEmailSenderService(EmailSenderService emailSenderService) {
// this.emailSenderService = emailSenderService;
// }
public EmailSenderService getEmailSenderService() {
return emailSenderService;
}
public void setEmailSenderService(EmailSenderService emailSenderService) {
this.emailSenderService = emailSenderService;
}
}

@ -54,6 +54,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceIm
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
@ -100,6 +101,12 @@ import java.util.List;
* policy="dynamic"
* bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
* @scr.reference name="email.sender.service"
* interface="org.wso2.carbon.email.sender.core.service.EmailSenderService"
* cardinality="0..1"
* policy="dynamic"
* bind="setEmailSenderService"
* unbind="unsetEmailSenderService"
*/
public class DeviceManagementServiceComponent {
@ -360,4 +367,18 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setConfigurationContextService(null);
}
protected void setEmailSenderService(EmailSenderService emailSenderService) {
if (log.isDebugEnabled()) {
log.debug("Setting Email Sender Service");
}
DeviceManagementDataHolder.getInstance().setEmailSenderService(emailSenderService);
}
protected void unsetEmailSenderService(EmailSenderService emailSenderService) {
if (log.isDebugEnabled()) {
log.debug("Un-setting Email Sender Service");
}
DeviceManagementDataHolder.getInstance().setEmailSenderService(null);
}
}

@ -47,6 +47,9 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.email.sender.core.ContentProviderInfo;
import org.wso2.carbon.email.sender.core.EmailContext;
import org.wso2.carbon.email.sender.core.EmailSendingFailedException;
import org.wso2.carbon.email.sender.core.TypedValue;
import org.wso2.carbon.user.api.UserStoreException;
@ -540,14 +543,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
new TypedValue<Class<?>, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl()));
params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP,
new TypedValue<Class<?>, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl()));
// try {
// EmailContext ctx =
// new EmailContext.EmailContextBuilder(new ContentProviderInfo("user-enrollment", params),
// metaInfo.getRecipients()).build();
//// DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx);
// } catch (EmailSendingFailedException e) {
// throw new DeviceManagementException("Error occurred while sending enrollment invitation", e);
// }
try {
EmailContext ctx =
new EmailContext.EmailContextBuilder(new ContentProviderInfo("user-enrollment", params),
metaInfo.getRecipients()).build();
DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx);
} catch (EmailSendingFailedException e) {
throw new DeviceManagementException("Error occurred while sending enrollment invitation", e);
}
}
@Override
@ -565,14 +568,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
new TypedValue<Class<?>, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl()));
params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP,
new TypedValue<Class<?>, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl()));
// try {
// EmailContext ctx =
// new EmailContext.EmailContextBuilder(new ContentProviderInfo("user-registration", params),
// metaInfo.getRecipients()).build();
// DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx);
// } catch (EmailSendingFailedException e) {
// throw new DeviceManagementException("Error occurred while sending user registration notification", e);
// }
try {
EmailContext ctx =
new EmailContext.EmailContextBuilder(new ContentProviderInfo("user-registration", params),
metaInfo.getRecipients()).build();
DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx);
} catch (EmailSendingFailedException e) {
throw new DeviceManagementException("Error occurred while sending user registration notification", e);
}
}
@Override

@ -90,6 +90,10 @@
<groupId>commons-lang.wso2</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
</dependencies>
<build>
@ -110,6 +114,7 @@
<Import-Package>
org.wso2.carbon.governance.api.*,
javax.xml.namespace;resolution:=optional,
org.wso2.carbon.device.mgt.core.*,
org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.common.license.mgt,

@ -24,9 +24,10 @@ import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationUtil;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationProcessor;
import javax.servlet.ServletContext;
import java.io.IOException;
@ -51,11 +52,15 @@ public class FeatureManagementLifecycleListener implements LifecycleListener {
ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) {
String profile = System.getProperty(DeviceManagementConstants.Common.PROPERTY_PROFILE);
if ((profile.equalsIgnoreCase(DeviceManagementConstants.Common.PROFILE_DT_WORKER) ||
profile.equalsIgnoreCase(DeviceManagementConstants.Common.PROFILE_DEFAULT)) && isManagedApi) {
try {
AnnotationUtil annotationUtil = new AnnotationUtil(context);
Set<String> annotatedAPIClasses = annotationUtil.scanStandardContext(DeviceType.class.getName());
Map<String, List<Feature>> features = annotationUtil.extractFeatures(annotatedAPIClasses);
AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
Set<String> annotatedAPIClasses = annotationProcessor.scanStandardContext(DeviceType.class.getName());
Map<String, List<Feature>> features = annotationProcessor.extractFeatures(annotatedAPIClasses);
if (features != null && !features.isEmpty()) {
GenericFeatureManager.getInstance().addFeatures(features);
}

@ -55,22 +55,23 @@ import java.util.Set;
/**
* This has the utility function to extract feature information.
*/
public class AnnotationUtil {
public class AnnotationProcessor {
private static final Log log = LogFactory.getLog(AnnotationUtil.class);
private static final Log log = LogFactory.getLog(AnnotationProcessor.class);
private static final String PACKAGE_ORG_APACHE = "org.apache";
private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework";
private static final String STRING_ARR = "string_arr";
private static final String STRING = "string";
private static final String METHOD = "method";
private Class<org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature>
featureAnnotationClazz;
private ClassLoader classLoader;
private ServletContext servletContext;
public AnnotationUtil(final StandardContext context) {
public AnnotationProcessor(final StandardContext context) {
servletContext = context.getServletContext();
classLoader = servletContext.getClassLoader();
}
@ -147,7 +148,7 @@ public class AnnotationUtil {
Map<String, Object> apiParams = new HashMap<>();
for (int i = 0; i < annotations.length; i++) {
Annotation currentAnnotation = annotations[i];
feature = processHttpMethodAnnotation(feature, currentAnnotation);
processHttpMethodAnnotation(apiParams, currentAnnotation);
if (currentAnnotation.annotationType().getName().equals(Path.class.getName())) {
String uri = getPathAnnotationValue(currentMethod);
apiParams.put("uri", uri);
@ -199,24 +200,20 @@ public class AnnotationUtil {
/**
* Read Method annotations indicating HTTP Methods
* @param feature
* @param currentAnnotation
* @return
*/
private Feature processHttpMethodAnnotation(Feature feature, Annotation currentAnnotation) {
private void processHttpMethodAnnotation(Map<String, Object> apiParams, Annotation currentAnnotation) {
//Extracting method with which feature is exposed
if (currentAnnotation.annotationType().getName().equals(GET.class.getName())) {
feature.setMethod(HttpMethod.GET);
apiParams.put(METHOD, HttpMethod.GET);
} else if (currentAnnotation.annotationType().getName().equals(POST.class.getName())) {
feature.setMethod(HttpMethod.POST);
apiParams.put(METHOD, HttpMethod.POST);
} else if (currentAnnotation.annotationType().getName().equals(OPTIONS.class.getName())) {
feature.setMethod(HttpMethod.OPTIONS);
apiParams.put(METHOD, HttpMethod.OPTIONS);
} else if (currentAnnotation.annotationType().getName().equals(DELETE.class.getName())) {
feature.setMethod(HttpMethod.DELETE);
apiParams.put(METHOD, HttpMethod.DELETE);
} else if (currentAnnotation.annotationType().getName().equals(PUT.class.getName())) {
feature.setMethod(HttpMethod.PUT);
apiParams.put(METHOD, HttpMethod.PUT);
}
return feature;
}
/**
@ -240,9 +237,6 @@ public class AnnotationUtil {
case "description":
feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING));
break;
case "type":
feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING));
break;
}
}
return feature;

@ -29,12 +29,17 @@
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
<outputDirectory>/</outputDirectory>
<outputDirectory>/jaggeryapps/devicemgt-cdmf/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/uuf-template-app</directory>
<outputDirectory>/</outputDirectory>
<outputDirectory>/jaggeryapps/devicemgt-cdmf/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
<fileSet>
<directory>${basedir}/src/main/resources/jaggery-modules</directory>
<outputDirectory>/jaggery-modules/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>

@ -0,0 +1,38 @@
<module name="utils" xmlns="http://wso2.org/projects/jaggery/module.xml">
<script>
<name>reflection</name>
<path>scripts/reflection/reflection.js</path>
</script>
<script>
<name>file</name>
<path>scripts/file/file.js</path>
</script>
<script>
<name>patterns</name>
<path>scripts/patterns/patterns.js</path>
</script>
<script>
<name>xml</name>
<path>scripts/xml/xml.js</path>
</script>
<script>
<name>request</name>
<path>scripts/request/request.js</path>
</script>
<script>
<name>response</name>
<path>scripts/response/response.js</path>
</script>
<script>
<name>time</name>
<path>scripts/time/time.js</path>
</script>
<script>
<name>url</name>
<path>scripts/url/url.js</path>
</script>
<script>
<name>exception</name>
<path>scripts/exception/exception.js</path>
</script>
</module>

@ -0,0 +1,62 @@
/*
* Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed 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.
*/
/**
* Description: The response of the currently invoked api enpoint is organized
*/
var exception = {};
var log = new Log('exception_module');
(function(exception) {
/**
*
* @param message The exception description
* @param code HTTP STATUS CODE related to the exception
* @return The error object
*/
exception.buildExceptionObject = function(message, code) {
var error = {};
error.message = message;
error.code = code;
return error;
};
exception.handleError = function (exception, type, code){
var constants = require('rxt').constants;
if (type == constants.THROW_EXCEPTION_TO_CLIENT) {
log.debug(exception);
var e = exceptionModule.buildExceptionObject(exception, code);
throw e;
} else if (type == constants.LOG_AND_THROW_EXCEPTION) {
log.error(exception);
throw exception;
} else if (type == constants.LOG_EXCEPTION_AND_TERMINATE) {
log.error(exception);
var msg = 'An error occurred while serving the request!';
var e = exceptionModule.buildExceptionObject(msg, constants.STATUS_CODES.INTERNAL_SERVER_ERROR);
throw e;
} else if (type == constants.LOG_EXCEPTION_AND_CONTINUE) {
log.debug(exception);
}
else {
log.error(exception);
throw e;
}
};
}(exception))

@ -0,0 +1,167 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var file = {};
(function() {
var log = new Log('utils-file');
var CONTENT_MAP = {
'js': 'application/javascript',
'css': 'text/css',
'csv': 'text/csv',
'html': 'text/html',
'json': 'application/json',
'png': 'image/png',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'svg': 'image/svg+xml',
'ttf': 'application/x-font-ttf',
'eot': 'application/vnd.ms-fontobject',
'woff': 'application/font-woff',
'otf': 'application/x-font-otf',
'zip': 'application/zip',
'xml': 'text/xml',
'xhtml': 'application/xhtml+xml',
'pdf': 'application/pdf'
};
/**
* The function checks whether a directory contains a particular file
* @param dir The directory in which the file must be checked
* @param file A File object if the file exists,else null
*/
file.getFileInDir = function(dir, fileName) {
var isFilePresent = false;
var files = dir.listFiles();
for (var index in files) {
if (files[index].getName() == fileName) {
return files[index];
}
}
return null;
};
/**
* The function returns the file extension of a filename
* @param file
* @return: The extension of the file
*/
file.getExtension = function(file) {
var baseFileName = file.getName();
//Break up the name by .
var baseNameComponents = baseFileName.split('.');
var extension = baseNameComponents[baseNameComponents.length - 1];
return extension;
};
/**
* The function obtains the MIME type based on the extension
* @param The extension
* @return The mime type
*/
file.getMimeType = function(extension) {
return CONTENT_MAP[extension];
};
/**
* The function returns the name of the file without the file extension
* @param file A file object
* @return: The name of the file without the extension
*/
file.getFileName = function(file) {
//Get the name of the file
var baseFileName = file.getName();
//Break up the name by .
var baseNameComponents = baseFileName.split('.');
//Get all of the components except the last one
baseNameComponents.splice(baseNameComponents.length - 1, 1);
return baseNameComponents.join('.');
};
/**
* The function returns the contents of a directory as a JSON object.The name of the
* file is used as the property names without the extensions.
* NOTE: The method will not traverse sub folders.
* @param The directory to be inspected
* @return A JSON object which contains the files in the directory
*/
file.getDirectoryContents = function(dir) {
var dirContents = {};
//Check if it is a directory
if (!dir.isDirectory()) {
log.info('Not a directory');
return dirContents;
}
//Obtain a list of all files
var files = this.getAllFiles(dir);
var name;
log.info('Files: ' + files);
//Create the directory object with each file been a property
for (var index in files) {
dirContents[this.getFileName(files[index])] = files[index];
}
return dirContents;
};
/**
* The function obtains a list of files that are not directories
* @param dir The directory to be inspected
* @return An array with all of the files in the directory
*/
file.getAllFiles = function(dir) {
var filesInDir = [];
if (!dir.isDirectory()) {
return filesInDir;
}
//Obtain a list of all files
var files = dir.listFiles();
for (var index in files) {
log.info('Checking file: ' + files[index].getName());
//Check if the file is a directory
if (!files[index].isDirectory()) {
filesInDir.push(files[index]);
}
}
return filesInDir;
};
/**
* The function returns a list of all file names in a directory
* @param dir The directory to be inspected
* @return {An array containing the name of all files in a directory
*/
file.getAllFileNames = function(dir) {
var files = dir.listFiles();
var list = [];
var fileName;
for (var index in files) {
if (files[index].isDirectory()) {
fileName=this.getFileName(files[index].getName());
list.push(fileName);
}
}
return list;
};
/**
* The function returns a list of all sub directories in a given directory
* @param dir The root directory
* @return: An array containing all sub directories
*/
file.getAllSubDirs = function(dir) {
var files = dir.listFiles();
var subDirs = [];
for (var index in files) {
if (files[index].isDirectory()) {
subDirs.push(files[index]);
}
}
return subDirs;
};
}());

@ -0,0 +1,128 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var patterns = {};
(function () {
var DEF_ERR_ARITY = 3;
var DEF_HANDLE_ARITY = 2;
var log = new Log('utils.patterns.GenericPipe');
function GenericPipe(options) {
this.errHandlerArity = DEF_ERR_ARITY || options.errArity;
this.handlerArity = DEF_HANDLE_ARITY || options.handlerArity;
this.plugins = [];
this.finalHandler = function () {
};
}
/**
*The function registers the provided plugin
*/
GenericPipe.prototype.plug = function (plugin, options) {
var options = options || {};
//Only a function
if (plugin instanceof Function) {
this.plugins.push({
handle: plugin,
options: options
});
}
//Is it a plugin object
else if (plugin instanceof Object) {
plugin.options = options;
this.plugins.push(plugin);
}
return this;
};
GenericPipe.prototype.finally = function (plugin) {
this.finalHandler = plugin;
return this;
};
GenericPipe.prototype.resolve = function (data, req, res, session) {
var context = {};
context.req = req;
context.res = res;
context.session = session;
context.data = data;
handle(context, this.plugins, this.errHandlerArity, this.handlerArity, this.finalHandler);
};
var handle = function (context, plugins, errArity, handlerArity, finallyHandler) {
var index = 0;
var currentPlugin;
var recursiveHandle = function (err) {
currentPlugin = plugins[index];
index++;
//Check if there is a plugin
if (!currentPlugin) {
//log.warn('No plugin found at index: ' + index);
return;
}
//Populate the options object for the plugin
context.options=currentPlugin.options;;
//Check if an error has been provided
if (err) {
//Can the current plugin handle the err
if (currentPlugin.handle.length == errArity) {
try {
currentPlugin.handle(err, context,recursiveHandle);
}
catch (e) {
recursiveHandle(e);
}
}
else {
recursiveHandle(err);
}
}
//There is no error so try to invoke the current plugin
else {
if (currentPlugin.handle.length == handlerArity) {
try {
currentPlugin.handle(context,recursiveHandle);
} catch (e) {
recursiveHandle(e);
}
}
else {
recursiveHandle();
}
}
};
recursiveHandle();
finallyHandler(context);
};
patterns.GenericPipe = GenericPipe;
}());

@ -0,0 +1,230 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var reflection = {};
/**
* Description: The script encapsulates any reflection related utility functions
*/
(function() {
var log = new Log('utils-reflection');
reflection.copyPropKeys = function(from, to) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
to[key] = '';
}
}
return to;
};
/**
* The function recursively copies all property keys in an object
* @param from
* @param to
*/
reflection.copyAllPropKeys = function(from, to) {
recurse(from, to, function(from, to, key) {
if (from[key] instanceof Object) {
to[key] = from[key];
} else {
to[key] = null;
}
});
};
reflection.copyAllPropValues = function(from, to) {
recurse(from, to, function(from, to, key) {
//Create an instance if the property does not exist
if (!to[key]) {
to[key] = {};
}
//Copy the values over
if (!(from[key] instanceof Object)) {
to[key] = from[key];
} else {
log.debug('Not copying values of key: ' + key);
}
});
};
/**
* The function will only copy public properties
* @param from
* @param to
*/
reflection.copyPublicPropValues = function(from, to) {
recurse(from, to, function(from, to, key) {
//Ignore any hidden properties
if (key.charAt(0) == '_') {
log.warn('Drop key: ' + key);
return;
}
//Create an instance if the property does not exist
if (!to[key]) {
to[key] = {};
}
//Copy the values over
if (!(from[key] instanceof Object)) {
to[key] = from[key];
} else {
log.warn('Not copying values of key: ' + key);
}
});
};
reflection.inspect = function(from, to, cb) {
recurse(from, to, cb);
};
/**
* The function recursively traverses an object and then invokes the provided
* callback
* @param root
* @param clone
* @param cb
*/
var recurse = function(root, clone, cb) {
var key;
//Check if the root is an object
if (!(root instanceof Object)) {
return;
} else {
var keys = Object.keys(root);
//Go through all the other keys in the current root
for (var index in keys) {
key = keys[index];
cb(root, clone, key);
recurse(root[key], clone[key], cb);
}
}
};
reflection.copyProps = function(from, to) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
to[key] = from[key];
}
}
return to;
};
reflection.getProps = function(obj) {
var props = {};
for (var key in obj) {
if (!(obj[key] instanceof Function)) {
props[key] = obj[key];
}
}
return props;
};
reflection.printProps = function(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
log.info('key: ' + key);
}
}
};
/**
* The function determines if a property is hidden based on _
* @param key
* @returns {boolean}
*/
reflection.isHiddenProp = function(key) {
if (key == '') {
return false;
}
return (key.charAt(0) == '_') ? true : false;
};
var getDiff = function(a, b, diff) {};
/**
* The function calculates the differences between two simple JSON objects
* @param a The object with which b is compared
* @param b The target of the comparison
* @return An object which records the differences between the two objects
*/
reflection.diff = function(a, b) {};
/**
* The function merges the two provided objects to create a new
* object.In the case where b has the same property as a; the property of b
* will have precedence
* @param {[type]} a [description]
* @param {[type]} b [description]
* @return A new object having the properties of both object a and b
*/
reflection.merge = function(a, b) {
var newObj = {};
//Copy the properties of a first
for (var key in a) {
newObj[key] = b[key];
}
//Override with the properties of b
for (var key in b) {
newObj[key] = b[key];
}
return newObj;
};
/**
* The function allows a child class to override a select set of methods of
* a parent class.The original methods of the parent can be accessed
* using the this._super keyword
* @param {[type]} parent The parent class instance to be overriden
* @param {[type]} child The child class instance containing methods which will override the parent
*/
reflection.override = function(parent, child) {
//Make a clone of the parent
var super = parse(stringify(parent));
for (var childKey in child) {
for (var parentKey in parent) {
//Only override those methods that are common
if (childKey === parentKey) {
var parentPtr = parent[parentKey];
var childPtr = child[childKey];
//Update the clone with the old parent method
super[parentKey] = parentPtr;
parent[parentKey] = childPtr;
/*parent[parentKey] = function() {
var result=childPtr.apply(this, arguments)||null;
return result;
};*/
}
}
}
//Allow the child object to call methods of the parent
parent._super = super;
};
reflection.overrideAll=function(parent,child){
//Make a clone of the parent
var super = parse(stringify(parent));
for (var childKey in child) {
for (var parentKey in parent) {
//Only override those methods that are common
if ( (child.hasOwnProperty(childKey))&&(parent.hasOwnProperty(parentKey)) ) {
var parentPtr = parent[parentKey];
var childPtr = child[childKey];
//Update the clone with the old parent method
super[parentKey] = parentPtr;
parent[parentKey] = childPtr;
/*parent[parentKey] = function() {
var result=childPtr.apply(this, arguments)||null;
return result;
};*/
}
}
}
//Allow the child object to call methods of the parent
parent._super = super;
};
reflection.isArray = function(object) {
if (Object.prototype.toString.call(object) === '[object Array]') {
return true;
}
return false;
};
}());

@ -0,0 +1,57 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var request = {};
(function(request) {
var hasOwnProperty = function(obj, element) {
return Object.prototype.hasOwnProperty.call(obj, element);
};
var isObject = function(object) {;
return typeof object === 'object';
};
/*
* ECMA Standard (ECMA-262 : 5.1 Edition)*/
var decodes = function(encodedURI) {
return decodeURIComponent(encodedURI);
};
request.getQueryOptions = function(queryString) {
var opt={};
var sep = opt.sep || '&',
assign = opt.assign || '=',
compoArray = [];
var obj = {};
var decodedURI = decodes(queryString);
decodedURI.split(sep).forEach(function(comp) {
comp.split(assign).some(function(element, index, array) {
if (hasOwnProperty(obj, element.toString())) {
compoArray.push(obj[element]);
compoArray.push(array[1]);
obj[element] = compoArray;
} else {
Object.defineProperty(obj, element, {
enumerable: true,
writable: true,
value: array[1]
});
}
return true;
});
});
return obj;
};
}(request))

@ -0,0 +1,96 @@
/*
* Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed 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.
*/
/**
* Description: The response of the currently invoked api endpoint is organized
*/
var response = {};
var log = new Log("response");
(function(response) {
/**
* Build Error response
* @param resp jaggery-response object to retrieve to client
* @param code status code
* @param message message to the client side
* @return return response
*/
response.buildErrorResponse = function(resp,code,message) {
var content={};
content.error = message;
resp = processResponse(resp,code,content);
return resp;
};
/**
* Build success response
* @param resp jaggery response object
* @param code status code
* @param data the result to client
* @return return response
*/
response.buildSuccessResponse= function(resp, code, data){
var content={};
content.data = data;
resp = processResponse(resp,code,content);
return resp;
};
/**
* process General response
* @param resp jaggery response
* @param code status code
* @param data success result
* @return resp jaggery response
*/
response.buildSuccessResponseForRxt= function(resp, code, data){
resp.status = code;
resp.content = data;
return resp;
};
/**
* General response builder
* @param resp jaggery response
* @param code status code
* @param content what ever the content to be sent as response
* @return resp jaggery response
*/
function processResponse(resp, code, content){
resp.status = code;
resp.contentType = 'application/json';
resp.content = content;
return resp;
};
/**
*
* @param resp
* @param code
* @param data
* @return The http response
*/
response.buildSuccessResponseForRxt= function(resp, code, data){
resp.contentType = 'application/json';
resp.status = code;
resp.content = data;
return resp;
};
}(response))

@ -0,0 +1,35 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var time = {};
(function(time) {
time.getCurrentTime = function(dateLength) {
var dateLength=dateLength||20;
var now = new String(new Date().valueOf());
var length = now.length;
var prefix = dateLength;
var onsetVal = '';
if (length != prefix) {
var onset = prefix - length;
for (var i = 0; i < onset; i++) {
onsetVal += '0';
}
}
return onsetVal + now;
};
}(time));

@ -0,0 +1,47 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var url = {};
(function() {
var log=new Log('utils-url');
url.popServerDetails = function(obj) {
var process = require('process');
var localIP = process.getProperty('server.host');
var httpPort = process.getProperty('http.port');
var httpsPort = process.getProperty('https.port');
var value = '';
var carbonLocalIP = process.getProperty('carbon.local.ip');
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
value = obj[key];
if ((typeof value === 'string') && value.indexOf('%https.host%') > -1) {
value=value.replace('%https.host%', 'https://' + localIP + ':' + httpsPort);
} else if ((typeof value === 'string') && value.indexOf('%http.host%') > -1) {
value=value.replace('%http.host%', 'http://' + localIP + ':' + httpPort);
} else if ((typeof value === 'string') && value.indexOf('%https.carbon.local.ip%') > -1) {
value=value.replace('%https.carbon.local.ip%', 'https://' + carbonLocalIP + ':' + httpsPort);
} else if ((typeof value === 'string') && value.indexOf('%http.carbon.local.ip%') > -1) {
value=value.replace('%http.carbon.local.ip%', 'http://' + carbonLocalIP + ':' + httpPort);
}
obj[key] = value;
}
}
return obj;
};
}(url));

@ -0,0 +1,138 @@
/*
* Copyright (c) 2005-2014, 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.
*
*/
var xml = {};
(function () {
var log=new Log('util.xml')
/*
The method is used to create a JSON object using
an xml object.
@xmlElement: An xml element object to be processed
@return: A pseudo object containing the properties of the
xml element.
*/
var createJSONObject = function (xmlElement) {
var pseudo = {};
//Extract all attributes
var attributes = xmlElement.@*;
//Fill the pseudo object with the attributes of the element
for (var attributeKey in attributes) {
var attribute = attributes[attributeKey];
pseudo[attribute.localName()] = attribute.toString();
}
return pseudo;
};
/*
The function converts an E4X Xml object to a JSON object
This function has been adapted from the work of Oleg Podsechin available at
https://gist.github.com/olegp/642667
It uses a slightly modified version of his algorithm , therefore
all credit should be attributed to Oleg Podsechin.
IMPORTANT:
1. It does not create a 1..1 mapping due to the differences
between Xml and JSON.It is IMPORTANT that you verify the structure
of the object generated before using it.
2. The input xml object must not contain the xml header information
This is a known bug 336551 (Mozilla Developer Network)
Source: https://developer.mozilla.org/en/docs/E4X
Please remove the header prior to sending the xml object for processing.
@root: A starting element in an E4X Xml object
@return: A JSON object mirroring the provided Xml object
*/
var recursiveConvertE4XtoJSON = function (root) {
log.debug('Root: ' + root.localName());
//Obtain child nodes
var children = root.*;
//The number of children
var numChildren = children.length();
//No children
if (numChildren == 0) {
//Extract contents
return createJSONObject(root);
}
else {
//Create an empty object
var rootObject = createJSONObject(root);
//Could be multiple children
for (var childElementKey in children) {
var child = children[childElementKey];
log.debug('Examining child: ' + child.localName());
//If the child just contains a single value then stop
if (child.localName() == undefined) {
log.debug('Child is undefined: ' + child.toString());
//Change the object to just a key value pair
rootObject[root.localName()] = child.toString();
return rootObject;
}
//Make a recursive call to construct the child element
var createdObject = recursiveConvertE4XtoJSON(child);
log.debug('Converted object: ' + stringify(createdObject));
//Check if the root object has the property
if (rootObject.hasOwnProperty(child.localName())) {
log.debug('key: ' + child.localName() + ' already present.');
rootObject[child.localName()].push(createdObject);
}
else {
log.debug('key: ' + child.localName() + ' not present.');
rootObject[child.localName()] = [];
rootObject[child.localName()].push(createdObject);
}
}
log.debug('root: ' + root.localName());
return rootObject;
}
};
/**
* The function is used to convert an E4X xml to JSON
* @param root
*/
xml.convertE4XtoJSON = function (root) {
return recursiveConvertE4XtoJSON(root);
};
}());

@ -1,62 +0,0 @@
<%
/*
* Copyright (c) 2015, 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.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("/api/operation-api.jag");
var utility = require('/app/modules/utility.js').utility;
var constants = require('/app/modules/constants.js');
var operationModule = require("/app/modules/operation.js").operationModule;
response.contentType = 'application/json';
var user = session.get(constants.USER_SESSION_KEY);
var result;
if (!user) {
response.sendRedirect("/devicemgt/login?#login-required");
exit();
} else {
if (uriMatcher.match("/{context}/api/operations/{deviceType}/stats")) {
var deviceType = uriMatcher.elements().deviceType;
var deviceId = request.getParameter("deviceId");
var monitorOperations = operationModule.getMonitorOperations(deviceType);
var stats = [];
result = {};
for (var op in monitorOperations) {
result = operationModule.handleGETOperation(deviceType, monitorOperations[op].operation, monitorOperations[op].name, deviceId);
stats.push(result.data);
}
result.data = stats;
} else if (uriMatcher.match("/{context}/api/operations/{deviceType}/{operation}")) {
var deviceType = uriMatcher.elements().deviceType;
var operation = uriMatcher.elements().operation;
var deviceId = request.getParameter("deviceId");
var params = request.getAllParameters();
result = operationModule.handlePOSTOperation(deviceType, operation, deviceId, params);
}
}
// returning the result.
if (result) {
print(result);
}
%>

@ -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.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/policy-api.jag");
var constants = require("/app/modules/constants.js");
var policyModule = require("/app/modules/policy.js").policyModule;
var deviceType, deviceId;
var user = session.get(constants.USER_SESSION_KEY);
var responseProcessor = require('utils').response;
response.contentType = 'application/json';
if (!user) {
response = responseProcessor.buildErrorResponse(response, 401, "Unauthorized");
} else {
if (uriMatcher.match("/{context}/api/policies/add")) {
var content = request.getContent();
var policyName = content.policyName;
var policyDefinition = content.profile.policyDefinition;
var policyDescription = content.profile.policyDescription;
deviceType = content.profile.deviceType.name;
deviceId = content.deviceId;
try {
response.content = policyModule.addPolicy(policyName, deviceType, policyDefinition,
policyDescription, deviceId);
} catch (e) {
log.error("Exception occurred while trying to add new policy under name:" + policyName, e);
// http status code 500 refers to - Internal Server Error.
responseProcessor.buildErrorResponse(response, 500, "Internal server error");
}
}
}
%>

@ -66,4 +66,17 @@ var groupModule = {};
);
};
groupModule.getGroupDevices = function (groupName, owner) {
endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices";
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return responsePayload;
}
);
};
}(groupModule));

@ -40,14 +40,11 @@ var operationModule = function () {
privateMethods.getOperationsFromFeatures = function (deviceType, operationType) {
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType;
var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
var features = responsePayload;
var featureList = [];
var feature;
for (var i = 0; i < features.length; i++) {
feature = {};
if (features[i].type != operationType) {
continue;
} else if (features[i].type == 'monitor') {
var features = responsePayload;
var featureList = [];
var feature;
for (var i = 0; i < features.length; i++) {
feature = {};
var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"];
if (analyticStreams) {
for (var stream in analyticStreams) {
@ -57,23 +54,22 @@ var operationModule = function () {
}
}
}
}
feature["operation"] = features[i].code;
feature["name"] = features[i].name;
feature["method"] = features[i].method;
feature["description"] = features[i].description;
feature["deviceType"] = deviceType;
feature["params"] = [];
var metaData = features[i].metadataEntries;
if (metaData) {
for (var j = 0; j < metaData.length; j++) {
feature["params"].push(metaData[j].value);
feature["operation"] = features[i].code;
feature["name"] = features[i].name;
feature["description"] = features[i].description;
feature["deviceType"] = deviceType;
feature["params"] = [];
var metaData = features[i].metadataEntries;
if (metaData) {
for (var j = 0; j < metaData.length; j++) {
feature["params"].push(metaData[j].value);
}
featureList.push(feature);
}
featureList.push(feature);
}
}
return featureList;
}, function (responsePayload) {
return featureList;
}, function (responsePayload) {
var response = {};
response["status"] = "error";
return response;

@ -129,7 +129,7 @@ utility = function () {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
var unitName = user.domain + "cdmf.unit.device.type." + deviceType + "." + unitPostfix;
var unitName = user.domain + ".cdmf.unit.device.type." + deviceType + "." + unitPostfix;
if (new File("/app/units/" + unitName).isExists()) {
return unitName;
}

@ -48,7 +48,8 @@
<div class="wr-input-control">
<button class="wr-btn" id="add-group-btn">
&nbsp;&nbsp;&nbsp;&nbsp;Add&nbsp;&nbsp;&nbsp;&nbsp;</button>
<button class="wr-btn" onclick="history.go(-1)">&nbsp;&nbsp;&nbsp;&nbsp;Cancel&nbsp;&nbsp;&nbsp;&nbsp;</button>
<button class="wr-btn" onclick="window.location = '{{@app.context}}/groups';return false;">
&nbsp;&nbsp;&nbsp;&nbsp;Cancel&nbsp;&nbsp;&nbsp;&nbsp;</button>
</div>
</form>
</div>

@ -15,8 +15,7 @@
<div class="wr-advance-operations">
<div class="row no-gutter">
<div class="wr-hidden-operations-nav col-lg-4">
<a href="javascript:void(0)" onclick="showAdvanceOperation('general', this)"
class="selected">
<a class="selected">
<span class="wr-hidden-operations-icon fw-stack">
<i class="fw fw-settings fw-stack-2x"></i>
</span>
@ -32,7 +31,6 @@
<div id="general-config-heading" class="panel-heading" role="tab">
<h2 class="sub-title panel-title">
Policy Monitoring
<hr>
</h2>
</div>
<div id="email-config-body" class="panel-collapse panel-body"
@ -88,3 +86,6 @@
<!-- /content -->
</div>
</div>
{{#zone "bottomJs"}}
{{js "js/platform-configuration.js"}}
{{/zone}}

@ -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.
*/
$(document).ready(function () {
var configParams = {
"NOTIFIER_TYPE": "notifierType",
"NOTIFIER_FREQUENCY": "notifierFrequency"
};
var responseCodes = {
"CREATED": "Created",
"SUCCESS": "201",
"INTERNAL_SERVER_ERROR": "Internal Server Error"
};
/**
* Checks if provided input is valid against RegEx input.
*
* @param regExp Regular expression
* @param inputString Input string to check
* @returns {boolean} Returns true if input matches RegEx
*/
function isPositiveInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
invokerUtil.get(
"/devicemgt_admin/configuration",
function (data) {
data = JSON.parse(data);
if (data && data.configuration) {
for (var i = 0; i < data.configuration.length; i++) {
var config = data.configuration[i];
if (config.name == configParams["NOTIFIER_FREQUENCY"]) {
$("input#monitoring-config-frequency").val(config.value / 1000);
}
}
}
}, function (data) {
console.log(data);
});
/**
* Following click function would execute
* when a user clicks on "Save" button
* on General platform configuration page in WSO2 EMM Console.
*/
$("button#save-general-btn").click(function () {
var notifierFrequency = $("input#monitoring-config-frequency").val();
var errorMsgWrapper = "#email-config-error-msg";
var errorMsg = "#email-config-error-msg span";
if (!notifierFrequency) {
$(errorMsg).text("Monitoring frequency is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (!isPositiveInteger(notifierFrequency)) {
$(errorMsg).text("Provided monitoring frequency is invalid. ");
$(errorMsgWrapper).removeClass("hidden");
} else {
var addConfigFormData = {};
var configList = new Array();
var monitorFrequency = {
"name": configParams["NOTIFIER_FREQUENCY"],
"value": String((notifierFrequency * 1000)),
"contentType": "text"
};
configList.push(monitorFrequency);
addConfigFormData.configuration = configList;
var addConfigAPI = "/devicemgt_admin/configuration";
invokerUtil.post(
addConfigAPI,
addConfigFormData,
function (data) {
data = JSON.parse(data);
if (data.statusCode == responseCodes["SUCCESS"]) {
$("#config-save-form").addClass("hidden");
$("#record-created-msg").removeClass("hidden");
} else if (data == 500) {
$(errorMsg).text("Exception occurred at backend.");
} else if (data == 403) {
$(errorMsg).text("Action was not permitted.");
} else {
$(errorMsg).text("An unexpected error occurred.");
}
$(errorMsgWrapper).removeClass("hidden");
}, function (data) {
data = data.status;
if (data == 500) {
$(errorMsg).text("Exception occurred at backend.");
} else if (data == 403) {
$(errorMsg).text("Action was not permitted.");
} else {
$(errorMsg).text("An unexpected error occurred.");
}
$(errorMsgWrapper).removeClass("hidden");
}
);
}
});
});

@ -254,7 +254,7 @@ $(document).ready(function () {
if (data.errorMessage) {
$(errorMsg).text("Selected user store prompted an error : " + data.errorMessage);
$(errorMsgWrapper).removeClass("hidden");
} else if (data["status"] == 201) {
} else if (data["statusCode"] == 201) {
// Clearing user input fields.
$("input#username").val("");
$("input#firstname").val("");
@ -265,17 +265,17 @@ $(document).ready(function () {
$("#user-create-form").addClass("hidden");
$("#user-created-msg").removeClass("hidden");
generateQRCode("#user-created-msg .qr-code");
} else if (data["status"] == 409) {
} else if (data["statusCode"] == 409) {
$(errorMsg).text(data["messageFromServer"]);
$(errorMsgWrapper).removeClass("hidden");
} else if (data["status"] == 500) {
} else if (data["statusCode"] == 500) {
$(errorMsg).text("An unexpected error occurred at backend server. Please try again later.");
$(errorMsgWrapper).removeClass("hidden");
}
}, function (data) {
if (data["status"] == 409) {
if (data["statusCode"] == 409) {
$(errorMsg).text("User : " + username + " already exists. Pick another username.");
} else if (data["status"] == 500) {
} else if (data["statusCode"] == 500) {
$(errorMsg).text("An unexpected error occurred at backend server. Please try again later.");
} else {
$(errorMsg).text(data.errorMessage);

@ -11,10 +11,6 @@
"url": "/api/groups/*",
"path": "/api/group-api.jag"
},
{
"url": "/api/operations/*",
"path": "/api/operation-api.jag"
},
{
"url": "/api/policies/*",
"path": "/api/policy-api.jag"

@ -53,6 +53,8 @@
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Policy Management Common Bundle</Bundle-Description>
<Import-Package>
javax.xml.bind.annotation,
io.swagger.annotations.*;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.core.dto.*,
javax.xml.bind.*,
@ -91,6 +93,11 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -17,6 +17,8 @@
*/
package org.wso2.carbon.policy.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.Device;
import javax.xml.bind.annotation.XmlElement;
@ -29,24 +31,50 @@ import java.util.Map;
* This class will be the used to create policy object with relevant information for evaluating.
*/
@XmlRootElement
@ApiModel(value = "Policy", description = "This class carries all information related to Policies")
public class Policy implements Comparable<Policy>, Serializable {
private static final long serialVersionUID = 19981017L;
@ApiModelProperty(name = "id", value = "The policy ID", required = true)
private int id; // Identifier of the policy.
private int priorityId; // Priority of the policies. This will be used only for simple evaluation.
@ApiModelProperty(name = "priorityId", value = "The priority order of the policy. 1 indicates the highest"
+ " priority", required = true)
private int priorityId; // Priority of the policies. This will be used only for simple evaluation.
@ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the "
+ "policy", required = true)
private Profile profile; // Profile
@ApiModelProperty(name = "policyName", value = "The name of the policy", required = true)
private String policyName; // Name of the policy.
@ApiModelProperty(name = "generic", value = "If true, this should be applied to all related device",
required = true)
private boolean generic; // If true, this should be applied to all related device.
@ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true)
private List<String> roles; // Roles which this policy should be applied.
@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"
+ "BYOD (Bring Your Own Device) - The policy will only be applied on the BYOD device type\n"
+ "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE "
+ "device type\n", required = true)
private String ownershipType; // Ownership type (COPE, BYOD, CPE)
@ApiModelProperty(name = "devices", value = "Lists out the devices the policy is enforced on",
required = true)
private List<Device> devices; // Individual devices this policy should be applied
@ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced",
required = true)
private List<String> users;
@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 = "updated", value = "If you have made changes to the policy but have not applied"
+ " these changes to the devices that are registered with EMM, then the value is defined as true."
+ " But if you have already applied any changes made to the policy then the value is defined as"
+ " false.", required = true)
private boolean updated;
@ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true)
private String description;
/* Compliance data*/
private String compliance;

@ -18,16 +18,29 @@
package org.wso2.carbon.policy.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(value = "ProfileFeature", description = "This class carries all information related to profile "
+ "features")
public class ProfileFeature implements Serializable {
private static final long serialVersionUID = 19981018L;
@ApiModelProperty(name = "id", value = "Define the ID", required = true)
private int id;
@ApiModelProperty(name = "featureCode", value = "Provide the code that defines the policy you wish to add",
required = true)
private String featureCode;
@ApiModelProperty(name = "profileId", value = "Define the ID of the profile", required = true)
private int profileId;
@ApiModelProperty(name = "deviceTypeId", value = "The ID used to define the type of the device platform",
required = true)
private int deviceTypeId;
@ApiModelProperty(name = "content", value = "The list of parameters that define the policy",
required = true)
private Object content;
public int getId() {

@ -1,72 +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.
*#
<EmailConfig>
<Subject>You have been invited to enroll your device in WSO2 EMM</Subject>
<Body>
<![CDATA[
<html>
<head>
<title>WSO2 Enterprise Mobility Manager</title>
</head>
<body style="color: #666666; background-color:#cdcdcd; padding: 0px; margin: 0px;">
<div style="background-color:#cdcdcd; font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; padding: 20px 0px; margin: 0px;">
<div style="width: 86%; max-width: 650px; padding: 2%; background-color: #ffffff; margin: auto; border-radius: 14px;">
<div style="background-color: #49c8f5; line-height: 0px; border-top-left-radius: 10px; border-top-right-radius: 10px; padding: 0px 10px 0px 0px;">
<div style="display: inline-block; line-height: 0px;">
<img src="http://b.content.wso2.com/sites/all/2015-june-theme/navigation/wso2-nav-logo.png"
alt="WSO2" style="margin: 0px 20px 0px 25px; width: 100%; max-width: 251px;"/>
</div>
</div>
<div style="background-color: #ffffff; line-height: 170%; color: #666666; padding: 20px 25px;">
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px 20px;">
Hi $first-name,
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
You have been invited to enrol your device in WSO2 Enterprise Mobility Manager.
Click <a href="$base-url-https/emm-web-agent/enrollment">here</a> to download the WSO2 EMM client application to begin device
enrolment.</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
Should you need assistance, please contact your administrator.
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 20px 0px 5px;">
Regards,
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
WSO2 EMM Administrator
</p>
</div>
<div style="background-color: #333333; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px;">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="padding: 0px 20px 0px 0px;"><img
src="http://b.content.wso2.com/newsletter/images/wso2-logo-cloud-footer.png" alt="WSO2"
style="margin: 15px 0px 15px 25px; width: 100%; max-width: 258px;"/></td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
]]>
</Body>
</EmailConfig>

@ -1,82 +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.
*#
<EmailConfig>
<Subject>You have successfully been registered in WSO2 EMM</Subject>
<Body>
<![CDATA[
<html>
<head>
<title>WSO2 Enterprise Mobility Manager</title>
</head>
<body style="color: #666666; background-color:#cdcdcd; padding: 0px; margin: 0px;">
<div style="background-color:#cdcdcd; font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; padding: 20px 0px; margin: 0px;">
<div style="width: 86%; max-width: 650px; padding: 2%; background-color: #ffffff; margin: auto; border-radius: 14px;">
<div style="background-color: #49c8f5; line-height: 0px; border-top-left-radius: 10px; border-top-right-radius: 10px; padding: 0px 10px 0px 0px;">
<div style="display: inline-block; line-height: 0px;">
<img src="http://b.content.wso2.com/sites/all/2015-june-theme/navigation/wso2-nav-logo.png"
alt="WSO2" style="margin: 0px 20px 0px 25px; width: 100%; max-width: 251px;"/>
</div>
</div>
<div style="background-color: #ffffff; line-height: 170%; color: #666666; padding: 20px 25px;">
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px 20px;">
Hi $first-name,
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
You have been registered in WSO2 Enterprise Mobility Manager and invited to enrol your device.
Click <a href="$base-url-https/emm-web-agent/enrollment">here</a> to download the WSO2 EMM client application to begin device
enrolment.</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
Use following credentials to log in to WSO2 EMM client application.
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
<b>Username:</b> $username
<br/>
<b>Password:</b> $password
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
Should you need assistance, please contact your administrator.
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 20px 0px 5px;">
Regards,
</p>
<p style="font-size: 1em; font-family: Arial, Helvetica; line-height: 170%; color: #666666; margin: 5px 0px;">
WSO2 EMM Administrator
</p>
</div>
<div style="background-color: #333333; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px;">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="padding: 0px 20px 0px 0px;"><img
src="http://b.content.wso2.com/newsletter/images/wso2-logo-cloud-footer.png" alt="WSO2"
style="margin: 15px 0px 15px 25px; width: 100%; max-width: 258px;"/></td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
]]>
</Body>
</EmailConfig>

@ -3,5 +3,4 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/license-config.xml,target:${installFolder}/../../conf/etc/license-config.xml,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/remote-appmanager-config.xml,target:${installFolder}/../../conf/etc/remote-appmanager-config.xml,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/dbscripts/cdm,target:${installFolder}/../../../dbscripts/cdm,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/rxts/license.rxt,target:${installFolder}/../../../repository/resources/rxts/license.rxt,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/rxts/license.rxt,target:${installFolder}/../../../repository/resources/rxts/license.rxt,overwrite:true);\

@ -57,7 +57,7 @@
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt-cdmf
${project.build.directory}/maven-shared-archive-resources
</outputDirectory>
<includes>**/*</includes>
</artifactItem>

@ -1,3 +1,4 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggeryapps/devicemgt-cdmf,target:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggeryapps/devicemgt-cdmf,target:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggery-modules/utils/,target:${installFolder}/../../modules/utils,overwrite:true);\

@ -1456,10 +1456,23 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<scm>
@ -1823,6 +1836,7 @@
<nimbus.orbit.version.range>[2.26.1, 3.0.0)</nimbus.orbit.version.range>
<swagger.version>1.5.8</swagger.version>
<servlet-api.version>2.5</servlet-api.version>
</properties>
</project>

Loading…
Cancel
Save