merging with master branch

feature/appm-store/pbac
lasantha 7 years ago
commit 667f997f34

@ -22,13 +22,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Annotations</name>
<description>WSO2 Carbon - API Management Custom Annotation Module</description>

@ -21,12 +21,12 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - API Application Management API</name>

@ -22,12 +22,12 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Application Management</name>

@ -21,13 +21,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Security Handler Component</name>
<description>WSO2 Carbon - API Management Security Handler Module</description>

@ -13,13 +13,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Client</name>
<description>WSO2 Carbon - API Management Integration Client</description>

@ -13,13 +13,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Generated Client</name>
<description>WSO2 Carbon - API Management Integration Client</description>

@ -22,13 +22,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Webapp Publisher</name>
<description>WSO2 Carbon - API Management Webapp Publisher</description>

@ -57,6 +57,7 @@ public class APIConfig {
private String tenantDomain;
private String[] tags;
private Set<ApiScope> scopes;
private boolean isDefault = true;
@XmlElement(name = "Policy", required = true)
public String getPolicy() {
@ -184,4 +185,13 @@ public class APIConfig {
public void setScopes(Set<ApiScope> scopes) {
this.scopes = scopes;
}
@XmlElement(name = "isDefault")
public boolean isDefault() {
return isDefault;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
}

@ -108,7 +108,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
api.setStatus(PUBLISHED_STATUS);
api.setResponseCaching("DISABLED");
api.setDestinationStatsEnabled("false");
api.isDefaultVersion(true);
api.isDefaultVersion(config.isDefault());
List<String> transport = new ArrayList<>();
transport.add("https");
transport.add("http");

@ -55,6 +55,7 @@ public class APIPublisherUtil {
private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints";
private static final String AUTH_TYPE_NON_SECURED = "None";
private static final String PARAM_IS_DEFAULT = "isDefault";
public static String getServerBaseUrl() {
WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance();
@ -143,6 +144,13 @@ public class APIPublisherUtil {
apiConfig.setSecured(false);
boolean isDefault = true;
String isDefaultParam = servletContext.getInitParameter(PARAM_IS_DEFAULT);
if (isDefaultParam != null && !isDefaultParam.isEmpty()) {
isDefault = Boolean.parseBoolean(isDefaultParam);
}
apiConfig.setDefault(isDefault);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {

@ -22,13 +22,13 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - API Management Extensions Component</name>
<url>http://wso2.org</url>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -0,0 +1,221 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ /*
~ * Copyright (c) ${date}, 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.
~ */
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.cert.admin.v09.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - Admin Certificate Management v09 API</name>
<description>WSO2 Carbon - Admin Certificate Management v09 API</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>api#certificate-mgt#v0.9</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>deploy</id>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<copy todir="${basedir}/../../../repository/deployment/server/webapps" overwrite="true">
<fileset dir="${basedir}/target">
<include name="api#certificate-mgt#v0.9.war" />
</fileset>
</copy>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>client</id>
<build>
<defaultGoal>test</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<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>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,417 @@
/*
*
* Copyright (c) ${date}, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* /
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Info;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Extension;
import io.swagger.annotations.Tag;
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.ResponseHeader;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import javax.validation.constraints.Size;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "0.9.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "Certificate Management"),
@ExtensionProperty(name = "context", value = "/api/certificate-mgt/v0.9/admin/certificates"),
})
}
),
tags = {
@Tag(name = "device_management", description = "")
}
)
@Api(value = "Certificate Management", description = "This API includes all the certificate management related operations")
@Path("/admin/certificates")
@Scopes(scopes = {
@Scope(
name = "Adding a new SSL certificate",
description = "Adding a new SSL certificate",
key = "perm:admin:certificates:add",
permissions = {"/device-mgt/admin/certificates/add"}
),
@Scope(
name = "Getting Details of an SSL Certificate",
description = "Getting Details of an SSL Certificate",
key = "perm:admin:certificates:details",
permissions = {"/device-mgt/admin/certificates/details"}
),
@Scope(
name = "Getting Details of Certificates",
description = "Getting Details of Certificates",
key = "perm:admin:certificates:view",
permissions = {"/device-mgt/admin/certificates/view"}
),
@Scope(
name = "Deleting an SSL Certificate",
description = "Deleting an SSL Certificate",
key = "perm:admin:certificates:delete",
permissions = {"/device-mgt/admin/certificates/delete"}
),
@Scope(
name = "Verify SSL certificate",
description = "Verify SSL certificate",
key = "perm:admin:certificates:verify",
permissions = {"/device-mgt/admin/certificates/verify"}
)
}
)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface CertificateManagementAdminService {
String SCOPE = "scope";
/**
* Save a list of certificates and relevant information in the database.
*
* @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as
* a pem and a serial number.
* @return Status of the data persist operation.
*/
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding a new SSL certificate",
notes = "Add a new SSL certificate to the client end database.\n",
tags = "Certificate Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:add")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "Created. \n Successfully added the certificate.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the added certificates."),
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 303,
message = "See Other. \n The source can be retrieved from the URL specified in the location header.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 415,
message = "Unsupported Media Type. \n The format of the requested entity was not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while adding certificates.",
response = ErrorResponse.class)
})
Response addCertificate(
@ApiParam(
name = "enrollmentCertificates",
value = "The properties to add a new certificate. It includes the following: \n" +
"serial: The unique ID of the certificate. \n" +
"pem: Convert the OpenSSL certificate to the .pem format and base 64 encode the file. \n" +
"INFO: Upload the .pem file and base 64 encode it using a tool, such as the base64encode.in tool.",
required = true) EnrollmentCertificate[] enrollmentCertificates);
/**
* Get a certificate when the serial number is given.
*
* @param serialNumber serial of the certificate needed.
* @return certificate response.
*/
@GET
@Path("/{serialNumber}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of an SSL Certificate",
notes = "Get the client side SSL certificate details.",
tags = "Certificate Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:details")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the certificate details.",
response = CertificateResponse.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified certificate does not exist."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the requested certificate information.",
response = ErrorResponse.class)
})
Response getCertificate(
@ApiParam(name = "serialNumber",
value = "The serial number of the certificate.",
required = true,
defaultValue = "124380353155528759302")
@PathParam("serialNumber") String serialNumber,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time.\n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince
);
/**
* Get all certificates in a paginated manner.
*
* @return paginated result of certificate.
*/
@GET
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Certificates",
notes = "Get all the details of the certificates you have used for mutual SSL. In a situation where you wish to "
+ "view all the certificate details, it is not feasible to show all the details on one "
+ "page. Therefore, the details are paginated.",
tags = "Certificate Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:view")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of certificates.",
response = CertificateList.class,
responseContainer = "List",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 303,
message = "See Other. \n " +
"The source can be retrieved from the URL specified in the location header.\n",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable. \n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the certificate details.",
response = ErrorResponse.class)
})
Response getAllCertificates(
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
required = false,
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many certificate details you require from the starting pagination index/offset.",
required = false,
defaultValue = "5")
@QueryParam("limit") int limit,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince);
@DELETE
@Path("/{serialNumber}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Deleting an SSL Certificate",
notes = "Delete an SSL certificate that's on the client end.",
tags = "Certificate Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:delete")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully removed the certificate."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while removing the certificate.",
response = ErrorResponse.class)})
Response removeCertificate(
@ApiParam(
name = "serialNumber",
value = "The serial number of the certificate.\n" +
"NOTE: Make sure that a certificate with the serial number you provide exists in the server. If not, first add a certificate.",
required = true,
defaultValue = "12438035315552875930")
@PathParam("serialNumber") String serialNumber);
/**
* Verify Certificate for the API security filter
*
* @param certificate to be verified as a String
* @return Status of the certificate verification.
*/
@POST
@Path("/verify/{type}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Verify SSL certificate",
notes = "Verify Certificate for the API security filter.\n",
tags = "Certificate Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:certificates:verify")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "Return the status of the certificate verification.",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class)
})
Response verifyCertificate(
@ApiParam(
name = "type",
value = "The device type, such as ios, android or windows.",
required = true,
allowableValues = "android, ios, windows")
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "certificate",
value = "The properties to verify certificate. It includes the following: \n" +
"serial: The unique ID of the certificate. (optional) \n" +
"pem: pem String of the certificate",
required = true) EnrollmentCertificate certificate);
}

@ -0,0 +1,35 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.Serializable;
public class InputValidationException extends WebApplicationException implements Serializable {
private static final long serialVersionUID = 147843589458906890L;
public InputValidationException(ErrorResponse error) {
super(Response.status(Response.Status.BAD_REQUEST).entity(error).build());
}
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class UnexpectedServerErrorException extends WebApplicationException {
private static final long serialVersionUID = 147943679458906890L;
public UnexpectedServerErrorException(ErrorResponse error) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
}
}

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

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

@ -0,0 +1,49 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
public class EnrollmentCertificate {
String serial;
String pem;
int tenantId;
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public String getPem() {
return pem;
}
public void setPem(String pem) {
this.pem = pem;
}
}

@ -0,0 +1,79 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
@ApiModel(description = "Error List Item")
public class ErrorListItem {
@NotNull
private String code = null;
@NotNull
private String message = null;
@ApiModelProperty(required = true, value = "")
@JsonProperty("code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ErrorListItem() {
}
public ErrorListItem(String code, String msg) {
this.code = code;
this.message = msg;
}
/**
* Description about individual errors occurred
*/
@ApiModelProperty(required = true, value = "Description about individual errors occurred")
@JsonProperty("message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("errorItem {\n");
sb.append(" code: ").append(code).append("\n");
sb.append(" message: ").append(message).append("\n");
sb.append("}\n");
return sb.toString();
}
}

@ -0,0 +1,193 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(description = "Error Response")
public class ErrorResponse {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> errorItems = new ArrayList<>();
private ErrorResponse() {
}
@JsonProperty(value = "code")
@ApiModelProperty(required = true, value = "")
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
@JsonProperty(value = "message")
@ApiModelProperty(required = true, value = "ErrorResponse message.")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@JsonProperty(value = "description")
@ApiModelProperty(value = "A detail description about the error message.")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty(value = "moreInfo")
@ApiModelProperty(value = "Preferably an url with more details about the error.")
public String getMoreInfo() {
return moreInfo;
}
public void setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
}
public void addErrorListItem(ErrorListItem item) {
this.errorItems.add(item);
}
/**
* If there are more than one error list them out. \nFor example, list out validation errors by each field.
*/
@JsonProperty(value = "errorItems")
@ApiModelProperty(value = "If there are more than one error list them out. \n" +
"For example, list out validation errors by each field.")
public List<ErrorListItem> getErrorItems() {
return errorItems;
}
public void setErrorItems(List<ErrorListItem> error) {
this.errorItems = error;
}
@Override
public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("{");
// boolean cont = false;
// if (code != null) {
// cont = true;
// sb.append(" \"code\": ").append(code);
// }
// if (message != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"message\": \"").append(message).append("\"");
// }
// if (description != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"description\": ").append(description).append("\"");
// }
// if (moreInfo != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"moreInfo\": \"").append(moreInfo).append("\"");
// }
// if (error != null && error.size() > 0) {
// if (cont) {
// sb.append(",");
// }
// sb.append(" \"errorItems\": ").append(error);
// }
// sb.append("}");
// return sb.toString();
return null;
}
public static class ErrorResponseBuilder {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> error;
public ErrorResponseBuilder() {
this.error = new ArrayList<>();
}
public ErrorResponseBuilder setCode(long code) {
this.code = code;
return this;
}
public ErrorResponseBuilder setMessage(String message) {
this.message = message;
return this;
}
public ErrorResponseBuilder setDescription(String description) {
this.description = description;
return this;
}
public ErrorResponseBuilder setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
return this;
}
public ErrorResponseBuilder addErrorItem(String code, String msg) {
ErrorListItem item = new ErrorListItem();
item.setCode(code);
item.setMessage(msg);
this.error.add(item);
return this;
}
public ErrorResponse build() {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(code);
errorResponse.setMessage(message);
errorResponse.setErrorItems(error);
errorResponse.setDescription(description);
errorResponse.setMoreInfo(moreInfo);
return errorResponse;
}
}
}

@ -0,0 +1,61 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
public class ValidationResponse {
private String JWTToken; // X-JWT-Assertion
private String deviceId;
private String deviceType;
private int tenantId;
public String getJWTToken() {
return JWTToken;
}
public void setJWTToken(String JWTToken) {
this.JWTToken = JWTToken;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

@ -0,0 +1,33 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
@Produces({ "application/json", "application/xml" })
public class ErrorHandler implements ExceptionMapper<MDMAPIException> {
public Response toResponse(MDMAPIException exception) {
ErrorMessage errorMessage = new ErrorMessage();
errorMessage.setErrorMessage(exception.getErrorMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common;
public class ErrorMessage {
private String errorMessage;
private String errorCode;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}

@ -0,0 +1,91 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@Provider
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> {
private Gson gson;
private static final String UTF_8 = "UTF-8";
public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
private Gson getGson() {
if (gson == null) {
final GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
}
return gson;
}
public Object readFrom(Class<Object> objectClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> stringStringMultivaluedMap, InputStream entityStream)
throws IOException, WebApplicationException {
InputStreamReader reader = new InputStreamReader(entityStream, "UTF-8");
try {
return getGson().fromJson(reader, type);
} finally {
reader.close();
}
}
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
public long getSize(Object o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}
public void writeTo(Object object, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> stringObjectMultivaluedMap, OutputStream entityStream)
throws IOException, WebApplicationException {
OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
try {
getGson().toJson(object, type, writer);
} finally {
writer.close();
}
}
}

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

@ -0,0 +1,31 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.exception;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class BadRequestException extends WebApplicationException {
public BadRequestException(Message message, MediaType mediaType) {
super(Response.status(Response.Status.BAD_REQUEST).entity(message).type(mediaType).build());
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.exception;
public class Message {
private String errorMessage;
private String discription;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
}

@ -0,0 +1,318 @@
/*
* Copyright (c) 2016-2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.CertificateManagementAdminService;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ValidationResponse;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.CertificateMgtAPIUtils;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.scep.SCEPException;
import org.wso2.carbon.certificate.mgt.core.scep.SCEPManager;
import org.wso2.carbon.certificate.mgt.core.scep.TenantedDeviceWrapper;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.certificate.mgt.core.service.PaginationResult;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("/admin/certificates")
public class CertificateManagementAdminServiceImpl implements CertificateManagementAdminService {
private static Log log = LogFactory.getLog(CertificateManagementAdminServiceImpl.class);
private static final String PROXY_AUTH_MUTUAL_HEADER = "proxy-mutual-auth-header";
/**
* Save a list of certificates and relevant information in the database.
*
* @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as
* a pem and a serial number.
* @return Status of the data persist operation.
*/
@POST
public Response addCertificate(EnrollmentCertificate[] enrollmentCertificates) {
CertificateManagementService certificateService;
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate;
certificateService = CertificateMgtAPIUtils.getCertificateManagementService();
try {
for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) {
certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
certificate.setSerial(enrollmentCertificate.getSerial());
certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem()));
certificates.add(certificate);
}
certificateService.saveCertificate(certificates);
return Response.status(Response.Status.CREATED).entity("Added successfully.").build();
} catch (KeystoreException e) {
String msg = "Error occurred while converting PEM file to X509Certificate.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
}
}
/**
* Get a certificate when the serial number is given.
*
* @param serialNumber serial of the certificate needed.
* @return certificate response.
*/
@GET
@Path("/{serialNumber}")
public Response getCertificate(
@PathParam("serialNumber") String serialNumber,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
RequestValidationUtil.validateSerialNumber(serialNumber);
CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService();
List<CertificateResponse> certificateResponse;
try {
certificateResponse = certificateService.searchCertificates(serialNumber);
return Response.status(Response.Status.OK).entity(certificateResponse).build();
} catch (CertificateManagementException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
}
}
/**
* Get all certificates in a paginated manner.
*
* @param offset index of the first record to be fetched
* @param limit number of records to be fetched starting from the start index.
* @return paginated result of certificate.
*/
@GET
public Response getAllCertificates(
@QueryParam("offset") int offset,
@QueryParam("limit") int limit,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
RequestValidationUtil.validatePaginationInfo(offset, limit);
CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService();
try {
PaginationResult result = certificateService.getAllCertificates(offset, limit);
CertificateList certificates = new CertificateList();
certificates.setCount(result.getRecordsTotal());
certificates.setList((List<CertificateResponse>) result.getData());
return Response.status(Response.Status.OK).entity(certificates).build();
} catch (CertificateManagementException e) {
String msg = "Error occurred while fetching all certificates.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@DELETE
@Deprecated
@Path("/{serialNumber}")
public Response removeCertificate(@PathParam("serialNumber") String serialNumber) {
RequestValidationUtil.validateSerialNumber(serialNumber);
CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService();
try {
certificateService.removeCertificate(serialNumber);
return Response.status(Response.Status.OK).entity(
"Certificate that carries the serial number '" +
serialNumber + "' has been removed").build();
} catch (CertificateManagementException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
// @POST
// @Path("/verify/ios")
// public Response verifyIOSCertificate(@ApiParam(name = "certificate", value = "Mdm-Signature of the " +
// "certificate that needs to be verified", required = true) EnrollmentCertificate certificate) {
// try {
// CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService();
// X509Certificate cert = certMgtService.extractCertificateFromSignature(certificate.getPem());
// String challengeToken = certMgtService.extractChallengeToken(cert);
//
// if (challengeToken != null) {
// challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim();
//
// SCEPManager scepManager = CertificateMgtAPIUtils.getSCEPManagerService();
// DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
// deviceIdentifier.setId(challengeToken);
// deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);
// TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier);
//
// if (tenantedDeviceWrapper != null) {
// return Response.status(Response.Status.OK).entity("valid").build();
// }
// }
// } catch (SCEPException e) {
// String msg = "Error occurred while extracting information from certificate.";
// log.error(msg, e);
// return Response.serverError().entity(
// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
// } catch (KeystoreException e) {
// String msg = "Error occurred while converting PEM file to X509Certificate.";
// log.error(msg, e);
// return Response.serverError().entity(
// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
// }
// return Response.status(Response.Status.OK).entity("invalid").build();
// }
//
// @POST
// @Path("/verify/android")
// public Response verifyAndroidCertificate(@ApiParam(name = "certificate", value = "Base64 encoded .pem file of the " +
// "certificate that needs to be verified", required = true) EnrollmentCertificate certificate) {
// CertificateResponse certificateResponse = null;
// try {
// CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService();
// if (certificate.getSerial().toLowerCase().contains(PROXY_AUTH_MUTUAL_HEADER)) {
// certificateResponse = certMgtService.verifySubjectDN(certificate.getPem());
// } else {
// X509Certificate clientCertificate = certMgtService.pemToX509Certificate(certificate.getPem());
// if (clientCertificate != null) {
// certificateResponse = certMgtService.verifyPEMSignature(clientCertificate);
// }
// }
//
// if (certificateResponse != null && certificateResponse.getCommonName() != null && !certificateResponse
// .getCommonName().isEmpty()) {
// return Response.status(Response.Status.OK).entity("valid").build();
// }
// } catch (KeystoreException e) {
// String msg = "Error occurred while converting PEM file to X509Certificate.";
// log.error(msg, e);
// return Response.serverError().entity(
// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
// }
// return Response.status(Response.Status.OK).entity("invalid").build();
// }
@POST
@Path("/verify/{type}")
public Response verifyCertificate(@PathParam("type") String type, EnrollmentCertificate certificate) {
try {
CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService();
if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS.equalsIgnoreCase(type)) {
X509Certificate cert = certMgtService.extractCertificateFromSignature(certificate.getPem());
String challengeToken = certMgtService.extractChallengeToken(cert);
if (challengeToken != null) {
challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim();
SCEPManager scepManager = CertificateMgtAPIUtils.getSCEPManagerService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(challengeToken);
deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);
TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier);
Map<String, String> claims = new HashMap<>();
claims.put("http://wso2.org/claims/enduserTenantId",
String.valueOf(tenantedDeviceWrapper.getTenantId()));
claims.put("http://wso2.org/claims/enduser",
tenantedDeviceWrapper.getDevice().getEnrolmentInfo().getOwner() + "@"
+ tenantedDeviceWrapper.getTenantDomain());
claims.put("http://wso2.org/claims/deviceIdentifier",
tenantedDeviceWrapper.getDevice().getDeviceIdentifier());
claims.put("http://wso2.org/claims/deviceIdType", tenantedDeviceWrapper.getDevice().getType());
String jwdToken;
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantId(tenantedDeviceWrapper.getTenantId());
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(tenantedDeviceWrapper.getTenantDomain());
JWTClientManagerService jwtClientManagerService = CertificateMgtAPIUtils
.getJwtClientManagerService();
jwdToken = jwtClientManagerService.getJWTClient()
.getJwtToken(tenantedDeviceWrapper.getDevice().getEnrolmentInfo().getOwner(), claims,
true);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
ValidationResponse validationResponse = new ValidationResponse();
validationResponse.setDeviceId(challengeToken);
validationResponse.setDeviceType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);
validationResponse.setJWTToken(jwdToken);
validationResponse.setTenantId(tenantedDeviceWrapper.getTenantId());
return Response.status(Response.Status.OK).entity(validationResponse).build();
}
}
if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID.equalsIgnoreCase(type)) {
CertificateResponse certificateResponse = null;
if (certificate.getSerial().toLowerCase().contains(PROXY_AUTH_MUTUAL_HEADER)) {
certificateResponse = certMgtService.verifySubjectDN(certificate.getPem());
} else {
X509Certificate clientCertificate = certMgtService.pemToX509Certificate(certificate.getPem());
if (clientCertificate != null) {
certificateResponse = certMgtService.verifyPEMSignature(clientCertificate);
}
}
if (certificateResponse != null && certificateResponse.getCommonName() != null && !certificateResponse
.getCommonName().isEmpty()) {
return Response.status(Response.Status.OK).entity("valid").build();
}
}
} catch (SCEPException e) {
String msg = "Error occurred while extracting information from certificate.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
} catch (KeystoreException e) {
String msg = "Error occurred while converting PEM file to X509Certificate.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
} catch (JWTClientException e) {
String msg = "Error occurred while converting PEM file to X509Certificate.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity("invalid").build();
}
}

@ -0,0 +1,61 @@
/*
*
* Copyright (c) ${date}, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* /
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.swagger.extension;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.jaxrs.Reader;
import io.swagger.jaxrs.config.ReaderListener;
import io.swagger.models.Swagger;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
import java.util.HashMap;
import java.util.Map;
@SwaggerDefinition(
basePath = "/api/certificate-mgt/v0.9",
host = "localhost:9443"
)
public class SecurityDefinitionConfigurator implements ReaderListener {
public static final String TOKEN_AUTH_SCHEME = "swagger_auth";
@Override
public void beforeScan(Reader reader, Swagger swagger) {
}
@Override
public void afterScan(Reader reader, Swagger swagger) {
OAuth2Definition tokenScheme = new OAuth2Definition();
tokenScheme.setType("oauth2");
tokenScheme.setFlow("application");
tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth2/token");
tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth2/authorize");
tokenScheme.addScope("write:everything", "Full access");
Map<String, SecuritySchemeDefinition> schemes = new HashMap<>();
schemes.put(TOKEN_AUTH_SCHEME, tokenScheme);
swagger.setSecurityDefinitions(schemes);
}
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
public void destroy() {
//do nothing
}
public void init(FilterConfig filterConfig) throws ServletException {
//do nothing
}
}

@ -0,0 +1,108 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.scep.SCEPManager;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import javax.ws.rs.core.MediaType;
/**
* CertificateMgtAPIUtils class provides utility functions used by Certificate Mgt REST-API classes.
*/
public class CertificateMgtAPIUtils {
public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE;
private static Log log = LogFactory.getLog(CertificateMgtAPIUtils.class);
public static CertificateManagementService getCertificateManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
CertificateManagementService certificateManagementService = (CertificateManagementService)
ctx.getOSGiService(CertificateManagementService.class, null);
if (certificateManagementService == null) {
String msg = "CertificateManagementAdminServiceImpl Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return certificateManagementService;
}
public static JWTClientManagerService getJwtClientManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
JWTClientManagerService jwtClientManagerService = (JWTClientManagerService)
ctx.getOSGiService(JWTClientManagerService.class, null);
if (jwtClientManagerService == null) {
String msg = "JWTClientManagerService Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return jwtClientManagerService;
}
public static SCEPManager getSCEPManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
SCEPManager scepManagerService = (SCEPManager)
ctx.getOSGiService(SCEPManager.class, null);
if (scepManagerService == null) {
String msg = "SCEPManagerImpl Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return scepManagerService;
}
public static MediaType getResponseMediaType(String acceptHeader) {
MediaType responseMediaType;
if (acceptHeader == null || MediaType.WILDCARD.equals(acceptHeader)) {
responseMediaType = DEFAULT_CONTENT_TYPE;
} else {
responseMediaType = MediaType.valueOf(acceptHeader);
}
return responseMediaType;
}
public static SearchManagerService getSearchManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
SearchManagerService searchManagerService =
(SearchManagerService) ctx.getOSGiService(SearchManagerService.class, null);
if (searchManagerService == null) {
String msg = "DeviceImpl search manager service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return searchManagerService;
}
}

@ -0,0 +1,48 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.InputValidationException;
public class RequestValidationUtil {
public static void validateSerialNumber(String serialNumber) {
if (serialNumber == null || serialNumber.isEmpty()) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Serial number cannot be null or empty").build());
}
}
public static void validatePaginationInfo(int offset, int limit) {
if (offset < 0) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Offset number cannot be negative").build());
}
if (limit < 0) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Limit number cannot be negative").build());
}
}
}

@ -0,0 +1,107 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ResponsePayload {
private int statusCode;
private String messageFromServer;
private Object responseContent;
@XmlElement
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@XmlElement
public String getMessageFromServer() {
return messageFromServer;
}
public void setMessageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
}
@XmlElement
public Object getResponseContent() {
return responseContent;
}
public void setResponseContent(Object responseContent) {
this.responseContent = responseContent;
}
private ResponsePayloadBuilder getBuilder() {
return new ResponsePayloadBuilder();
}
public static ResponsePayloadBuilder statusCode(int statusCode) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().statusCode(statusCode);
}
public static ResponsePayloadBuilder messageFromServer(String messageFromServer) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().messageFromServer(messageFromServer);
}
public static ResponsePayloadBuilder responseContent(String responseContent) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().responseContent(responseContent);
}
public class ResponsePayloadBuilder {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public ResponsePayloadBuilder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public ResponsePayloadBuilder messageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
return this;
}
public ResponsePayloadBuilder responseContent(String responseContent) {
this.responseContent = responseContent;
return this;
}
public ResponsePayload build() {
ResponsePayload payload = new ResponsePayload();
payload.setStatusCode(statusCode);
payload.setMessageFromServer(messageFromServer);
payload.setResponseContent(responseContent);
return payload;
}
}
}

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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 file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
For ex:
Actual API endpoint: devicemgt_admin/1.0.0/devices/{device-id}
URL to be represented here: /devices/*
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- CertificateManagementAdminService related APIs -->
<Permission>
<name>View all certificates</name>
<path>/device-mgt/admin/certificate/GetAll</path>
<url>/admin/certificates</url>
<method>GET</method>
</Permission>
<Permission>
<name>Add certificate</name>
<path>/device-mgt/admin/certificate/Add</path>
<url>/admin/certificates</url>
<method>POST</method>
</Permission>
<Permission>
<name>Remove certificate</name>
<path>/device-mgt/admin/certificate/Remove</path>
<url>/admin/certificates/*</url>
<method>DELETE</method>
</Permission>
<Permission>
<name>View certificate</name>
<path>/device-mgt/admin/certificate/View</path>
<url>/admin/certificates/*</url>
<method>GET</method>
</Permission>
<!-- End of CertificateManagementAdminService related APIs -->
</PermissionConfiguration>

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ /*
~ * Copyright (c) ${date}, 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.
~ */
-->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
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="services" address="/">
<jaxrs:serviceBeans>
<ref bean="certificateServiceBean"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
<ref bean="swaggerWriter"/>
</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.certificate.mgt.cert.jaxrs.api"/>
<property name="version" value="0.9.0"/>
<property name="host" value="localhost:9443"/>
<property name="schemes" value="https" />
<property name="basePath" value="/api-certificate-mgt-v0.9"/>
<property name="title" value="Certificate Management Admin Service API Definitions"/>
<property name="contact" value="dev@wso2.org"/>
<property name="license" value="Apache 2.0"/>
<property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<property name="scan" value="true"/>
</bean>
<bean id="certificateServiceBean" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl.CertificateManagementAdminServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.GsonMessageBodyHandler"/>
<bean id="errorHandler" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.ErrorHandler"/>
</beans>

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Certificate-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS Certificate Management Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<init-param>
<param-name>swagger.security.filter</param-name>
<param-value>ApiAuthorizationFilterImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>isDefault</param-name>
<param-value>false</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<security-constraint>
<web-resource-collection>
<web-resource-name>CertificateMgt-Admin</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.ApiOriginFilter</filter-class>
</filter>
<filter>
<filter-name>HttpHeaderSecurityFilter</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<init-param>
<param-name>hstsEnabled</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter>
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
<filter-class>org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter</filter-class>
<init-param>
<param-name>patterns</param-name>
<param-value>text/html" ,application/json" ,text/plain</param-value>
</init-param>
<init-param>
<param-name>filterAction</param-name>
<param-value>enforce</param-value>
</init-param>
<init-param>
<param-name>httpHeaders</param-name>
<param-value>Cache-Control: no-store, no-cache, must-revalidate, private</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HttpHeaderSecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

@ -21,13 +21,13 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Certificate Management Core</name>
<description>WSO2 Carbon - Certificate Management Core</description>

@ -323,19 +323,25 @@ public class CertificateGenerator {
CertificateResponse lookUpCertificate = null;
KeyStoreReader keyStoreReader = new KeyStoreReader();
if (distinguishedName != null && !distinguishedName.isEmpty()) {
LdapName ldapName;
try {
ldapName = new LdapName(distinguishedName);
} catch (InvalidNameException e) {
throw new KeystoreException(
"Invalid name exception while trying to create a LDAP name using the distinguished name ", e);
}
for (Rdn relativeDistinuguishedNames : ldapName.getRdns()) {
if (relativeDistinuguishedNames.getType().equalsIgnoreCase("CN")) {
System.err.println("CN is: " + relativeDistinuguishedNames.getValue());
lookUpCertificate = keyStoreReader
.getCertificateBySerial(String.valueOf(relativeDistinuguishedNames.getValue()));
break;
if (distinguishedName.contains("/CN=")) {
String[] dnSplits = distinguishedName.split("/CN=");
String commonNameExtracted = dnSplits[dnSplits.length - 1];
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
} else {
LdapName ldapName;
try {
ldapName = new LdapName(distinguishedName);
} catch (InvalidNameException e) {
throw new KeystoreException(
"Invalid name exception while trying to create a LDAP name using the distinguished name ",
e);
}
for (Rdn relativeDistinguishedNames : ldapName.getRdns()) {
if (relativeDistinguishedNames.getType().equalsIgnoreCase("CN")) {
lookUpCertificate = keyStoreReader
.getCertificateBySerial(String.valueOf(relativeDistinguishedNames.getValue()));
break;
}
}
}
}

@ -0,0 +1,224 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ /*
~ * Copyright (c) ${date}, 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.
~ */
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.v09.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - Certificate Management v09 API</name>
<description>WSO2 Carbon - Certificate Management v09 API</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>api#scep-mgt#v0.9</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>deploy</id>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<copy todir="${basedir}/../../../repository/deployment/server/webapps" overwrite="true">
<fileset dir="${basedir}/target">
<include name="api-scep-mgt-v0.9.war" />
</fileset>
</copy>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>client</id>
<build>
<defaultGoal>test</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<exclusions>
<exclusion>
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,117 @@
/*
*
* Copyright (c) ${date}, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* /
*/
package org.wso2.carbon.certificate.mgt.jaxrs.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "0.9.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "SCEP Management"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v0.9/scep"),
})
}
),
tags = {
@Tag(name = "scep_management", description = "SCEP management related REST-API. " +
"This can be used to manipulated device " +
"certificate related details.")
}
)
@Path("/scep")
@Api(value = "SCEP Management", description = "This API carries all device Certificate management " +
"related operations.")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Scopes(scopes = {
@Scope(
name = "Sign CSR",
description = "Sign CSR",
key = "perm:sign-csr",
permissions = {"/device-mgt/certificates/manage"}
)
}
)
public interface CertificateMgtService {
String SCOPE = "scope";
/**
* Sign the client's certificate signing request and save it in the database.
*
* @param binarySecurityToken Base64 encoded Certificate signing request.
* @return X509Certificate type sign certificate.
*/
@POST
@Path("/sign-csr")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiOperation(
consumes = MediaType.TEXT_PLAIN,
produces = MediaType.TEXT_PLAIN,
httpMethod = "POST",
value = "Process a given CSR and return signed certificates.",
notes = "This will return a signed certificate upon a given CSR.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:sign-csr")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the device location.",
response = String.class),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while retrieving signed certificate.",
response = ErrorResponse.class)
})
Response getSignedCertFromCSR(
@ApiParam(
name = "If-Modified-Since",
value = "Validates if the requested variant has not been modified since the time specified",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince,
String binarySecurityToken);
}

@ -0,0 +1,33 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.jaxrs.api.common;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
@Produces({ "application/json", "application/xml" })
public class ErrorHandler implements ExceptionMapper<MDMAPIException> {
public Response toResponse(MDMAPIException exception) {
ErrorMessage errorMessage = new ErrorMessage();
errorMessage.setErrorMessage(exception.getErrorMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.jaxrs.api.common;
public class ErrorMessage {
private String errorMessage;
private String errorCode;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}

@ -0,0 +1,91 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.jaxrs.api.common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@Provider
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> {
private Gson gson;
private static final String UTF_8 = "UTF-8";
public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
private Gson getGson() {
if (gson == null) {
final GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
}
return gson;
}
public Object readFrom(Class<Object> objectClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> stringStringMultivaluedMap, InputStream entityStream)
throws IOException, WebApplicationException {
InputStreamReader reader = new InputStreamReader(entityStream, "UTF-8");
try {
return getGson().fromJson(reader, type);
} finally {
reader.close();
}
}
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
public long getSize(Object o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}
public void writeTo(Object object, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> stringObjectMultivaluedMap, OutputStream entityStream)
throws IOException, WebApplicationException {
OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
try {
getGson().toJson(object, type, writer);
} finally {
writer.close();
}
}
}

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

@ -0,0 +1,56 @@
package org.wso2.carbon.certificate.mgt.jaxrs.api.impl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator;
import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.certificate.mgt.jaxrs.exception.UnexpectedServerErrorException;
import org.wso2.carbon.certificate.mgt.jaxrs.api.CertificateMgtService;
import org.wso2.carbon.certificate.mgt.jaxrs.exception.Message;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
@Path("/scep")
public class CertificateMgtServiceImpl implements CertificateMgtService {
private static Log log = LogFactory.getLog(CertificateMgtServiceImpl.class);
@POST
@Path("/sign-csr")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
public Response getSignedCertFromCSR(
@HeaderParam("If-Modified-Since") String ifModifiedSince, String binarySecurityToken) {
Message message = new Message();
X509Certificate signedCert;
String singedCertificate;
Base64 base64 = new Base64();
CertificateGenerator certificateGenerator = new CertificateGenerator();
try {
if (certificateGenerator.getSignedCertificateFromCSR(binarySecurityToken) == null) {
message.setErrorMessage("Error occurred while signing the CSR.");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity(message).build();
} else {
signedCert = certificateGenerator.getSignedCertificateFromCSR(binarySecurityToken);
singedCertificate = base64.encodeToString(signedCert.getEncoded());
return Response.status(Response.Status.OK).entity(singedCertificate).build();
}
} catch (KeystoreException e) {
String msg = "Error occurred while fetching certificate.";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode(
500l).setMessage(msg).build());
} catch (CertificateEncodingException e) {
String msg = "Error occurred while encoding the certificate.";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode(
500l).setMessage(msg).build());
}
}
}

@ -0,0 +1,107 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.jaxrs.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ResponsePayload {
private int statusCode;
private String messageFromServer;
private Object responseContent;
@XmlElement
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@XmlElement
public String getMessageFromServer() {
return messageFromServer;
}
public void setMessageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
}
@XmlElement
public Object getResponseContent() {
return responseContent;
}
public void setResponseContent(Object responseContent) {
this.responseContent = responseContent;
}
private ResponsePayloadBuilder getBuilder() {
return new ResponsePayloadBuilder();
}
public static ResponsePayloadBuilder statusCode(int statusCode) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().statusCode(statusCode);
}
public static ResponsePayloadBuilder messageFromServer(String messageFromServer) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().messageFromServer(messageFromServer);
}
public static ResponsePayloadBuilder responseContent(String responseContent) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().responseContent(responseContent);
}
public class ResponsePayloadBuilder {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public ResponsePayloadBuilder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public ResponsePayloadBuilder messageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
return this;
}
public ResponsePayloadBuilder responseContent(String responseContent) {
this.responseContent = responseContent;
return this;
}
public ResponsePayload build() {
ResponsePayload payload = new ResponsePayload();
payload.setStatusCode(statusCode);
payload.setMessageFromServer(messageFromServer);
payload.setResponseContent(responseContent);
return payload;
}
}
}

@ -0,0 +1,79 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
@ApiModel(description = "Error List Item")
public class ErrorListItem {
@NotNull
private String code = null;
@NotNull
private String message = null;
@ApiModelProperty(required = true, value = "")
@JsonProperty("code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ErrorListItem() {
}
public ErrorListItem(String code, String msg) {
this.code = code;
this.message = msg;
}
/**
* Description about individual errors occurred
*/
@ApiModelProperty(required = true, value = "Description about individual errors occurred")
@JsonProperty("message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("errorItem {\n");
sb.append(" code: ").append(code).append("\n");
sb.append(" message: ").append(message).append("\n");
sb.append("}\n");
return sb.toString();
}
}

@ -0,0 +1,193 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(description = "Error Response")
public class ErrorResponse {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> errorItems = new ArrayList<>();
private ErrorResponse() {
}
@JsonProperty(value = "code")
@ApiModelProperty(required = true, value = "")
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
@JsonProperty(value = "message")
@ApiModelProperty(required = true, value = "ErrorResponse message.")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@JsonProperty(value = "description")
@ApiModelProperty(value = "A detail description about the error message.")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty(value = "moreInfo")
@ApiModelProperty(value = "Preferably an url with more details about the error.")
public String getMoreInfo() {
return moreInfo;
}
public void setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
}
public void addErrorListItem(ErrorListItem item) {
this.errorItems.add(item);
}
/**
* If there are more than one error list them out. \nFor example, list out validation errors by each field.
*/
@JsonProperty(value = "errorItems")
@ApiModelProperty(value = "If there are more than one error list them out. \n" +
"For example, list out validation errors by each field.")
public List<ErrorListItem> getErrorItems() {
return errorItems;
}
public void setErrorItems(List<ErrorListItem> error) {
this.errorItems = error;
}
@Override
public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("{");
// boolean cont = false;
// if (code != null) {
// cont = true;
// sb.append(" \"code\": ").append(code);
// }
// if (message != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"message\": \"").append(message).append("\"");
// }
// if (description != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"description\": ").append(description).append("\"");
// }
// if (moreInfo != null) {
// if (cont) {
// sb.append(",");
// }
// cont = true;
// sb.append(" \"moreInfo\": \"").append(moreInfo).append("\"");
// }
// if (error != null && error.size() > 0) {
// if (cont) {
// sb.append(",");
// }
// sb.append(" \"errorItems\": ").append(error);
// }
// sb.append("}");
// return sb.toString();
return null;
}
public static class ErrorResponseBuilder {
private Long code = null;
private String message = null;
private String description = null;
private String moreInfo = null;
private List<ErrorListItem> error;
public ErrorResponseBuilder() {
this.error = new ArrayList<>();
}
public ErrorResponseBuilder setCode(long code) {
this.code = code;
return this;
}
public ErrorResponseBuilder setMessage(String message) {
this.message = message;
return this;
}
public ErrorResponseBuilder setDescription(String description) {
this.description = description;
return this;
}
public ErrorResponseBuilder setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
return this;
}
public ErrorResponseBuilder addErrorItem(String code, String msg) {
ErrorListItem item = new ErrorListItem();
item.setCode(code);
item.setMessage(msg);
this.error.add(item);
return this;
}
public ErrorResponse build() {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(code);
errorResponse.setMessage(message);
errorResponse.setErrorItems(error);
errorResponse.setDescription(description);
errorResponse.setMoreInfo(moreInfo);
return errorResponse;
}
}
}

@ -0,0 +1,31 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.jaxrs.exception;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class BadRequestException extends WebApplicationException {
public BadRequestException(Message message, MediaType mediaType) {
super(Response.status(Response.Status.BAD_REQUEST).entity(message).type(mediaType).build());
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.jaxrs.exception;
public class Message {
private String errorMessage;
private String discription;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.certificate.mgt.jaxrs.exception;
import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class UnexpectedServerErrorException extends WebApplicationException {
private static final long serialVersionUID = 147943679458906890L;
public UnexpectedServerErrorException(ErrorResponse error) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
}
}

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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 file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
For ex:
Actual API endpoint: devicemgt_admin/1.0.0/devices/{device-id}
URL to be represented here: /devices/*
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/certificate/GetSignCSR</path>
<url>/certificates/scep/signcsr</url>
<method>POST</method>
<scope>emm_admin</scope>
</Permission>
</PermissionConfiguration>

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ /*
~ * Copyright (c) ${date}, 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.
~ */
-->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
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="services" address="/">
<jaxrs:serviceBeans>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
<ref bean="swaggerWriter"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="certificateService" address="/certificates">
<jaxrs:serviceBeans>
<ref bean="certificateServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers"/>
<bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource"/>
<bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig">
<property name="resourcePackage" value="org.wso2.carbon.certificate.mgt.jaxrs"/>
<property name="version" value="0.9.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="certificateServiceBean" class="org.wso2.carbon.certificate.mgt.jaxrs.api.impl.CertificateMgtServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.certificate.mgt.jaxrs.api.common.GsonMessageBodyHandler"/>
<bean id="errorHandler" class="org.wso2.carbon.certificate.mgt.jaxrs.api.common.ErrorHandler"/>
</beans>

@ -0,0 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>Certificate-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS Certificate Management Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>isDefault</param-name>
<param-value>false</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<filter>
<filter-name>HttpHeaderSecurityFilter</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<init-param>
<param-name>hstsEnabled</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter>
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
<filter-class>org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter</filter-class>
<init-param>
<param-name>patterns</param-name>
<param-value>text/html" ,application/json" ,text/plain</param-value>
</init-param>
<init-param>
<param-name>filterAction</param-name>
<param-value>enforce</param-value>
</init-param>
<init-param>
<param-name>httpHeaders</param-name>
<param-value>Cache-Control: no-store, no-cache, must-revalidate, private</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HttpHeaderSecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

@ -22,14 +22,14 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - Certificate Management Component</name>
<url>http://wso2.org</url>
@ -37,7 +37,9 @@
<modules>
<module>org.wso2.carbon.certificate.mgt.core</module>
<module>org.wso2.carbon.certificate.mgt.api</module>
<module>org.wso2.carbon.certificate.mgt.cert.admin.api</module>
<module>org.wso2.carbon.certificate.mgt.cert.admin.api</module>
<module>org.wso2.carbon.certificate.mgt.cert.admin.v09.api</module>
<module>org.wso2.carbon.certificate.mgt.v09.api</module>
</modules>
<build>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -0,0 +1,52 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import java.util.List;
@ApiModel(value = "RemoteSessionInfo", description = "Template of the remote session")
public class RemoteSessionInfo {
@ApiModelProperty(name = "Server Url", value = "Url of the remote session server.", required = true)
private String serverUrl;
@ApiModelProperty(name = "isEnabled", value = "Is remote session functionality enabled", required = true)
private Boolean isEnabled;
public String getServerUrl() {
return serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public Boolean getEnabled() {
return isEnabled;
}
public void setEnabled(Boolean enabled) {
isEnabled = enabled;
}
}

@ -227,6 +227,70 @@ public interface ActivityInfoProviderService {
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince);
@GET
@Path("/type/{operationCode}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Activity Details",
notes = "Get the details of the operations/activities executed by the server on the devices registered" +
" with WSO2 EMM, during a defined time period.",
tags = "Activity Info Provider",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the activity details.",
response = ActivityList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 401,
message = "Unauthorized. \n Unauthorized request."),
@ApiResponse(
code = 404,
message = "Not Found. \n No activities found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the activity data.",
response = ErrorResponse.class)
})
Response getActivities(
@ApiParam(
name = "operationCode",
value = "Operation Code of the Activity",
required = true)
@PathParam("operationCode") String operationCode,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
required = true,
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many activity details you require from the starting pagination index/offset.",
required = true,
defaultValue = "5")
@QueryParam("limit") int limit);
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,

@ -546,6 +546,64 @@ public interface DeviceAgentService {
@ApiParam(name = "operation", value = "Operation object with data.", required = true)
@Valid Operation operation);
@PUT
@Path("/properties/{type}/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
consumes = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update Properties",
notes = "Update device properties.",
tags = "Device Agent Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:modify")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the operations.",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest " +
"version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No device is found under the provided type and id.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving information requested device.",
response = ErrorResponse.class)
})
Response updateDeviceProperties(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true)
@PathParam("type") String type,
@ApiParam(name = "id", value = "The device id.", required = true)
@PathParam("id") String deviceId,
@ApiParam(name = "properties", value = "device properties list.", required = true)
@Valid List<Device.Property> properties);
@GET
@Path("/status/operations/{type}/{id}")
@ApiOperation(

@ -81,7 +81,7 @@ import javax.ws.rs.core.Response;
)
@Path("/geo-services")
@Api(value = "Geo Service",
description = "This carries all the resources related to the geo service functionalities.")
description = "This carries all the resources related to the geo service functionalities.")
public interface GeoLocationBasedService {
/**
* Retrieve Analytics for the device type
@ -152,6 +152,79 @@ public interface GeoLocationBasedService {
required = true)
@QueryParam("to") long to);
/**
* Get data to show device locations in a map
*/
@GET
@Path("stats/deviceLocations")
@ApiOperation(
consumes = "application/json",
produces = "application/json",
httpMethod = "GET",
value = "Retrieve locations of devices",
notes = "",
response = Response.class,
tags = "Geo Service Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK.",
response = Response.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid parameters found.",
response = Response.class),
@ApiResponse(
code = 401,
message = "Unauthorized. \n Unauthorized request."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error on retrieving stats",
response = Response.class)
})
Response getGeoDeviceLocations(
@ApiParam(
name = "minLat",
value = "minimum latitude",
required = true)
@QueryParam("minLat") double minLat,
@ApiParam(
name = "maxLat",
value = "maxmimum latitude",
required = true)
@QueryParam("maxLat") double maxLat,
@ApiParam(
name = "minLong",
value = "minimum longitude",
required = true)
@QueryParam("minLong") double minLong,
@ApiParam(
name = "maxLong",
value = "maximum longitudeude",
required = true)
@QueryParam("maxLong") double maxLong,
@ApiParam(
name = "zoom",
value = "zoom level",
required = true)
@QueryParam("zoom") int zoom);
/**
* Create Geo alerts
*/

@ -209,4 +209,32 @@ public interface NotificationManagementService {
defaultValue = "1")
@PathParam("id") @Max(45)
int id);
@PUT
@Path("/clear-all")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Clear all notifications",
notes = "When a user needs to mark all the notifications as checked/read this " +
"function can be used to clear all notifications",
tags = "Device Notification Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:notifications:mark-checked")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK"),
@ApiResponse(
code = 500,
message = "Error occurred while clearing notifications.")
}
)
Response clearAllNotifications();
}

@ -0,0 +1,130 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.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.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.ResponseHeader;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import javax.validation.constraints.Size;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "remote_session_services"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/remote-session-services"),
})
}
),
tags = {
@Tag(name = "device_management", description = "")
}
)
@Scopes(
scopes = {
@Scope(
name = "Remote Session Connection",
description = "",
key = "perm:remote-session-service:connect",
permissions = {"/device-mgt/devices/owning-device/remote-session"}
)
}
)
@Path("/remote-session-services")
@Api(value = "Remote Session Service",
description = "This carries all the resources related to the remote session service functionality.")
public interface RemoteSessionService {
/**
* Retrieve Analytics for the device type
*/
@GET
@Path("connection/{deviceType}/{deviceId}")
@ApiOperation(
consumes = "application/json",
produces = "application/json",
httpMethod = "GET",
value = "Retrieve Connection Information for the device type",
notes = "",
response = Response.class,
tags = "Remote Session Service Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:remote-session-service:connect")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK.",
response = Response.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid Device Identifiers found.",
response = Response.class),
@ApiResponse(
code = 401,
message = "Unauthorized. \n Unauthorized request."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error on retrieving stats",
response = Response.class)
})
Response getRemoteSessionDeviceConnect(
@ApiParam(
name = "deviceId",
value = "The registered device Id.",
required = true)
@PathParam("deviceId") String deviceId,
@ApiParam(
name = "device-type",
value = "The device type, such as ios, android or windows.",
required = true)
@PathParam("deviceType")
@Size(max = 45)
String deviceType);
}

@ -115,6 +115,48 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
}
}
@GET
@Override
@Path("/type/{operationCode}")
public Response getActivities(@PathParam("operationCode") String operationCode,
@QueryParam("offset") int offset, @QueryParam("limit") int limit){
if (log.isDebugEnabled()) {
log.debug("getActivities -> Operation Code : " +operationCode+ "offset " + offset + " limit: " + limit );
}
RequestValidationUtil.validatePaginationParameters(offset, limit);
Response response = validateAdminUser();
if(response == null){
List<Activity> activities;
ActivityList activityList = new ActivityList();
DeviceManagementProviderService dmService;
try {
if (log.isDebugEnabled()) {
log.debug("Calling database to get activities for the operation code :" +operationCode);
}
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activities = dmService.getFilteredActivities(operationCode, limit, offset);
activityList.setList(activities);
if (log.isDebugEnabled()) {
log.debug("Calling database to get activity count.");
}
int count = dmService.getTotalCountOfFilteredActivities(operationCode);
if (log.isDebugEnabled()) {
log.debug("Activity count: " + count);
}
activityList.setCount(count);
return Response.ok().entity(activityList).build();
} catch (OperationManagementException e) {
String msg
= "ErrorResponse occurred while fetching the activities for the given operation code.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
} else {
return response;
}
}
@GET
@Override

@ -22,6 +22,7 @@ import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import io.swagger.annotations.ApiParam;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -518,6 +519,38 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
}
}
@Override
@PUT
@Path("/operations/{type}/{id}")
public Response updateDeviceProperties(@PathParam("type") String type, @PathParam("id") String deviceId,
@Valid List<Device.Property> properties) {
try {
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
String errorMessage = "Device type is invalid";
log.error(errorMessage);
return Response.status(Response.Status.BAD_REQUEST).build();
}
if(properties == null) {
String errorMessage = "Properties cannot be empty";
log.error(errorMessage);
return Response.status(Response.Status.BAD_REQUEST).build();
}
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type);
if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) {
String msg = "Device not found for identifier '" + deviceId + "'";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
DeviceMgtAPIUtils.getDeviceManagementService().updateProperties(deviceIdentifier, properties);
} catch (DeviceManagementException e) {
String errorMessage = "Issue in retrieving device management service instance";
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
return null;
}
@GET
@Path("/status/operations/{type}/{id}")
public Response getOperationsByDeviceAndStatus(@PathParam("type") String type, @PathParam("id") String deviceId,

@ -595,10 +595,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceManagementProviderService dms;
try {
RequestValidationUtil.validateDeviceIdentifier(type, id);
dms = DeviceMgtAPIUtils.getDeviceManagementService();
result = dms.getOperations(new DeviceIdentifier(id, type), request);
operationsList.setList((List<? extends Operation>) result.getData());
operationsList.setCount(result.getRecordsTotal());
return Response.status(Response.Status.OK).entity(operationsList).build();

@ -33,12 +33,13 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.common.geo.service.Event;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.geo.service.*;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate;
import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy;
import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
@ -47,15 +48,7 @@ import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
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.Response;
import java.util.ArrayList;
import java.util.HashMap;
@ -110,11 +103,11 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain);
AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI();
List<SearchResultEntry> searchResults = analyticsDataAPI.search(tenantId, tableName, query,
0,
100,
sortByFields);
0,
100,
sortByFields);
List<Event> events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList<String>(),
searchResults);
searchResults);
return Response.ok().entity(events).build();
} catch (AnalyticsException | UserStoreException e) {
log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e);
@ -127,6 +120,34 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
}
}
@Path("stats/deviceLocations")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getGeoDeviceLocations(
@QueryParam("minLat") double minLat,
@QueryParam("maxLat") double maxLat,
@QueryParam("minLong") double minLong,
@QueryParam("maxLong") double maxLong,
@QueryParam("zoom") int zoom) {
GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy();
GeoCoordinate southWest = new GeoCoordinate(minLat, minLong);
GeoCoordinate northEast = new GeoCoordinate(maxLat, maxLong);
int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom);
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
List<GeoCluster> geoClusters;
try {
geoClusters = deviceManagementService.findGeoClusters(southWest, northEast, geohashLength);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving geo clusters ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().entity(geoClusters).build();
}
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
@POST
@Consumes("application/json")
@ -312,11 +333,11 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain);
AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI();
List<SearchResultEntry> searchResults = analyticsDataAPI.search(tenantId, tableName, query,
0,
100,
sortByFields);
0,
100,
sortByFields);
List<Event> events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList<String>(),
searchResults);
searchResults);
return Response.ok().entity(events).build();
} catch (AnalyticsException | UserStoreException e) {
log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e);

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
@ -102,4 +103,18 @@ public class NotificationManagementServiceImpl implements NotificationManagement
}
}
@Override
public Response clearAllNotifications() {
Notification.Status status = Notification.Status.CHECKED;
try {
int loggedinUserTenantId = CarbonContext.getThreadLocalCarbonContext()
.getTenantId();
DeviceMgtAPIUtils.getNotificationManagementService().updateAllNotifications(status, loggedinUserTenantId);
return Response.status(Response.Status.OK).build();
} catch (NotificationManagementException e) {
log.error("Error encountered while trying to clear all notifications.", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
}

@ -0,0 +1,68 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.remote.session.RemoteSessionConfiguration;
import org.wso2.carbon.device.mgt.jaxrs.beans.RemoteSessionInfo;
import org.wso2.carbon.device.mgt.jaxrs.service.api.RemoteSessionService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
* The api for
*/
public class RemoteSessionServiceImpl implements RemoteSessionService {
private static Log log = LogFactory.getLog(RemoteSessionServiceImpl.class);
@Path("connect/{deviceType}/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getRemoteSessionDeviceConnect(@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType) {
//First, check whether the remote session is enabled.
RemoteSessionInfo sessionInfo = new RemoteSessionInfo();
sessionInfo.setEnabled(false);
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
.getDeviceManagementConfig();
if (deviceManagementConfig != null) {
RemoteSessionConfiguration remoteSessionConfiguration = deviceManagementConfig.getRemoteSessionConfiguration();
if (remoteSessionConfiguration != null) {
boolean isEnabled = remoteSessionConfiguration.isEnabled();
sessionInfo.setEnabled(isEnabled);
if (isEnabled) {
sessionInfo.setServerUrl(remoteSessionConfiguration.getRemoteSessionServerUrl());
}
return Response.ok().entity(sessionInfo).build();
}
}
return Response.ok().entity(sessionInfo).build();
}
}

@ -604,28 +604,22 @@ public class RoleManagementServiceImpl implements RoleManagementService {
private List<String> getRolesFromUserStore(String filter, String userStore) throws UserStoreException {
AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
String[] roles;
boolean filterRolesByName = (!((filter == null) || filter.isEmpty()));
if ((filter == null) || filter.isEmpty()) {
filter = "*";
} else {
filter += "*";
}
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
if (userStore.equals("all")) {
roles = userStoreManager.getRoleNames("*", -1, false, true, true);
roles = userStoreManager.getRoleNames(filter, -1, true, true, true);
} else {
roles = userStoreManager.getRoleNames(userStore + "/*", -1, false, true, true);
roles = userStoreManager.getRoleNames(userStore + "/" + filter, -1, true, true, true);
}
// removing all internal roles, roles created for Service-providers and application related roles.
List<String> filteredRoles = new ArrayList<>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith(
"Application/"))) {
if (!filterRolesByName) {
filteredRoles.add(role);
} else {
if (role.contains(filter)) {
filteredRoles.add(role);
}
}
}
filteredRoles.add(role);
}
return filteredRoles;
}

@ -222,14 +222,13 @@ public class DeviceMgtAPIUtils {
public static UserStoreCountRetriever getUserStoreCountRetrieverService()
throws UserStoreCounterException {
throws UserStoreCounterException, UserStoreException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
List<Object> countRetrieverFactories = ctx.getOSGiServices(AbstractCountRetrieverFactory.class, null);
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
RealmConfiguration realmConfiguration = realmService.getBootstrapRealmConfiguration();
String userStoreType;
//Ignoring Sonar warning as getUserStoreClass() returning string name of the class. So cannot use 'instanceof'.
if (JDBCUserStoreManager.class.getName().equals(realmConfiguration.getUserStoreClass())) {
if(DeviceMgtAPIUtils.getUserStoreManager() instanceof JDBCUserStoreManager) {
userStoreType = JDBCCountRetrieverFactory.JDBC;
} else {
userStoreType = InternalCountRetrieverFactory.INTERNAL;

@ -38,6 +38,7 @@
<ref bean="userManagementAdminService"/>
<ref bean="groupManagementService"/>
<ref bean="geoService"/>
<ref bean="remoteSessionService"/>
<ref bean="groupManagementAdminService"/>
<ref bean="applicationManagementAdminService"/>
<ref bean="deviceTypeManagementAdminService"/>
@ -81,6 +82,7 @@
<bean id="userManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.UserManagementServiceImpl"/>
<bean id="groupManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.GroupManagementServiceImpl"/>
<bean id="geoService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.GeoLocationBasedServiceImpl"/>
<bean id="remoteSessionService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.RemoteSessionServiceImpl"/>
<bean id="deviceManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceManagementAdminServiceImpl"/>
<bean id="applicationManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.ApplicationManagementAdminServiceImpl"/>
<bean id="groupManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.GroupManagementAdminServiceImpl"/>
@ -99,4 +101,4 @@
</cxf:inInterceptors>
</cxf:bus>
</beans>
</beans>

@ -30,6 +30,7 @@ import org.testng.IObjectFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.caching.impl.CacheImpl;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -93,7 +94,6 @@ public class DeviceAgentServiceTest {
private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
private static final String TEST_DEVICE_IDENTIFIER = "11222334455";
private static final String AUTHENTICATED_USER = "admin";
private static final String TENANT_DOMAIN = "carbon.super";
private static final String MONITOR_OPERATION = "POLICY_MONITOR";
private static Device demoDevice;
@ -119,35 +119,32 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test device Enrollment when the device is null")
public void testEnrollDeviceWithDeviceIsNULL() {
public void testEnrollDeviceWithNullDevice() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceAgentService.enrollDevice(null);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
}
@Test(description = "Test device enrollment when device type is null.")
public void testEnrollDeviceWithDeviceTypeNull() {
public void testEnrollDeviceWithNullDeviceType() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Device device = DeviceMgtAPITestHelper.generateDummyDevice(null, TEST_DEVICE_IDENTIFIER);
Response response = this.deviceAgentService.enrollDevice(device);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
}
@Test(description = "Test device enrollment of a device with null device identifier.")
public void testEnrollNewDeviceWithDeviceIdentifierIsNull() {
public void testEnrollNewDeviceWithNullDeviceIdentifier() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, null);
Response response = this.deviceAgentService.enrollDevice(device);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
@ -173,12 +170,10 @@ public class DeviceAgentServiceTest {
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser"))
.toReturn(AUTHENTICATED_USER);
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
demoDevice.setEnrolmentInfo(enrolmentInfo);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice);
Response response = this.deviceAgentService.enrollDevice(demoDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -187,12 +182,11 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test the device enrollment with device management exception.")
public void testEnrollDeviceWithException() throws DeviceManagementException {
public void testEnrollDeviceWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser"))
.toReturn(AUTHENTICATED_USER);
Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
@ -200,7 +194,6 @@ public class DeviceAgentServiceTest {
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device);
Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any()))
.thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.enrollDevice(device);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
@ -221,7 +214,7 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test dis-enrolling non existing device.")
public void testDisEnrollNonExistingDevice() throws DeviceManagementException {
public void testDisEnrollWithNonExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
@ -230,8 +223,8 @@ public class DeviceAgentServiceTest {
"The response status should be 204");
}
@Test(description = "Test dis-enrolling device error")
public void testDisEnrollingDeviceError() throws DeviceManagementException {
@Test(description = "Test dis-enrolling device where device management exception is thrown.")
public void testDisEnrollingDeviceWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any())).thenThrow(new
@ -244,14 +237,13 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test device update scenario with device management exception.")
public void testUpdateDeviceDMException() throws DeviceManagementException {
public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new
DeviceManagementException());
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -263,20 +255,18 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, null);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
}
@Test(description = "Test the update device scenario when there is no enrolled device.")
public void testUpdatingNonExistingDevice() throws DeviceManagementException {
public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(null);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
"The response status should be 404");
@ -284,14 +274,13 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test update device with device access authorization exception.")
public void testEnrollDeviceWithDeviceAccessAuthException() throws DeviceManagementException,
public void testEnrollDeviceWithDeviceAccessAuthorizationException() throws DeviceManagementException,
DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceAccessAuthorizationException());
@ -311,7 +300,6 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(false);
@ -324,16 +312,15 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test update device when device modification is unsuccessful.")
public void testUpdateDeviceNOTModify() throws DeviceManagementException, DeviceAccessAuthorizationException {
public void testUpdateDeviceWithUnsuccessfulDeviceModification() throws DeviceManagementException,
DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true);
@ -347,20 +334,20 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test updating device when modify enrollment throws exception")
public void testUpdateDeviceWithModifyEnrollmentFailure() throws DeviceManagementException, DeviceAccessAuthorizationException {
public void testUpdateDeviceWithModifyEnrollmentFailure() throws DeviceManagementException,
DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenThrow(new DeviceManagementException());
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any()))
.thenThrow(new DeviceManagementException());
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
@ -377,9 +364,7 @@ public class DeviceAgentServiceTest {
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true);
@ -396,14 +381,13 @@ public class DeviceAgentServiceTest {
public void testPublishEventsWithNullPayload() {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(this.privilegedCarbonContext.getTenantDomain())
.thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Map<String, Object> payload = null;
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
List<Object> payloadList = null;
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
@ -413,47 +397,47 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test publish events with no device access authorization.")
public void testPublishEventsWithOutAuthorization() throws DeviceAccessAuthorizationException {
public void testPublishEventsWithoutAuthorization() throws DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(false);
Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(this.privilegedCarbonContext.getTenantDomain())
.thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Map<String, Object> payload = new HashMap<>();
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
"The response status should be 401");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
"The response status should be 401");
Mockito.reset(this.deviceAccessAuthorizationService);
}
@Test
public void testPublishEventsWithDeviceAccessAuthException() throws DeviceAccessAuthorizationException {
@Test(description = "Test publish events when device access authorization exception is thrown.")
public void testPublishEventsWithDeviceAccessAuthorizationException() throws DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
.toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceAccessAuthorizationException());
Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(this.privilegedCarbonContext.getTenantDomain())
.thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Map<String, Object> payload = new HashMap<>();
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -461,30 +445,28 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test event publishing when the event stream dao is null.")
public void testEventPublishWithNullEventAttributesAndNullEventStreamDefDAO() throws DeviceAccessAuthorizationException, RemoteException {
public void testEventPublishWithNullEventAttributesAndNullEventStreamDefDAO()
throws DeviceAccessAuthorizationException, RemoteException {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
.toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
.toReturn(this.eventStreamAdminServiceStub);
Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString())).thenReturn(null);
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
@ -511,22 +493,19 @@ public class DeviceAgentServiceTest {
Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{});
EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class,
Mockito.RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")).toReturn
(eventPublisherService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService"))
.toReturn(eventPublisherService);
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -552,31 +531,29 @@ public class DeviceAgentServiceTest {
Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{});
EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class,
Mockito.RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")).toReturn
(eventPublisherService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService"))
.toReturn(eventPublisherService);
Mockito.when(eventPublisherService.publishEvent(Mockito.anyString(), Mockito.anyString(), Mockito.any(),
Mockito.any(), Mockito.any())).thenReturn(true);
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList,
TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200");
}
@Test(description = "Test event publishing when PublishEvents throws DataPublisherConfigurationException.")
public void testPublishEventsDataPublisherConfig() throws DeviceAccessAuthorizationException, RemoteException, DataPublisherConfigurationException {
public void testPublishEventsDataPublisherConfigurationException() throws DeviceAccessAuthorizationException,
RemoteException, DataPublisherConfigurationException {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
@ -599,24 +576,20 @@ public class DeviceAgentServiceTest {
Mockito.when(eventPublisherService.publishEvent(Mockito.anyString(), Mockito.anyString(), Mockito.any(),
Mockito.any(), Mockito.any())).thenThrow(
new DataPublisherConfigurationException("meta data[0] should have the device Id field"));
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
}
@Test(description = "Test Publish events with Axis Fault.")
@ -631,17 +604,15 @@ public class DeviceAgentServiceTest {
.toThrow(new AxisFault(""));
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -659,7 +630,6 @@ public class DeviceAgentServiceTest {
.toThrow(new RemoteException());
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
@ -669,7 +639,8 @@ public class DeviceAgentServiceTest {
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -687,7 +658,6 @@ public class DeviceAgentServiceTest {
.toThrow(new JWTClientException());
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
@ -697,7 +667,8 @@ public class DeviceAgentServiceTest {
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -715,7 +686,6 @@ public class DeviceAgentServiceTest {
.toThrow(new UserStoreException());
Map<String, Object> payload = new HashMap<>();
CacheImpl cache = Mockito.mock(CacheImpl.class);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
.toReturn(cache);
@ -725,7 +695,8 @@ public class DeviceAgentServiceTest {
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -753,9 +724,7 @@ public class DeviceAgentServiceTest {
.toReturn(false);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(),
@ -771,9 +740,7 @@ public class DeviceAgentServiceTest {
.toReturn(true);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertNotNull(response.getEntity(), "Response entity should not be null.");
@ -783,16 +750,15 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test the scenario when get pending operations throw OperationManagementException.")
public void testGetPendingOperationsWithOperationManagementException() throws DeviceManagementException, OperationManagementException {
public void testGetPendingOperationsWithOperationManagementException() throws DeviceManagementException,
OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier"))
.toReturn(true);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getPendingOperations(Mockito.any())).thenThrow(new
OperationManagementException());
Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
@ -811,7 +777,6 @@ public class DeviceAgentServiceTest {
.toReturn(true);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertNotNull(response.getEntity(), "Response entity should not be null.");
@ -825,8 +790,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(new ArrayList<String>() {
});
.thenReturn(new ArrayList<String>() {});
Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
@ -842,9 +806,7 @@ public class DeviceAgentServiceTest {
.toReturn(false);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
@ -860,9 +822,7 @@ public class DeviceAgentServiceTest {
.toReturn(true);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertNotNull(response.getEntity(), "Response entity should not be null.");
@ -872,18 +832,17 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test get next pending operation with operation management exception.")
public void getNextPendingOperationWithOperationManagementException() throws DeviceManagementException, OperationManagementException {
public void getNextPendingOperationWithOperationManagementException() throws DeviceManagementException,
OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier"))
.toReturn(true);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getNextPendingOperation(Mockito.any())).thenThrow(new
OperationManagementException());
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getNextPendingOperation(Mockito.any())).thenThrow(
new OperationManagementException());
Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertNotNull(response.getEntity(), "Response entity should not be null.");
@ -900,7 +859,6 @@ public class DeviceAgentServiceTest {
.toReturn(true);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertNotNull(response.getEntity(), "Response entity should not be null.");
@ -914,10 +872,8 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(new ArrayList<String>() {
});
.thenReturn(new ArrayList<String>() {});
Operation operation = new Operation();
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -930,11 +886,9 @@ public class DeviceAgentServiceTest {
public void testUpdateOperationWithNullOperation() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
null);
Assert.assertNotNull(response, "The response should not be null");
@ -949,13 +903,10 @@ public class DeviceAgentServiceTest {
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier"))
.toReturn(false);
Operation operation = new Operation();
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -970,13 +921,10 @@ public class DeviceAgentServiceTest {
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier"))
.toReturn(true);
Operation operation = new Operation();
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -986,7 +934,8 @@ public class DeviceAgentServiceTest {
}
@Test(description = "Test the update Operation method with Policy Monitoring Operation.")
public void testUpdateOperationSuccessWithPolicyMonitorOperation() throws DeviceManagementException, PolicyComplianceException {
public void testUpdateOperationSuccessWithPolicyMonitorOperation() throws DeviceManagementException,
PolicyComplianceException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier"))
@ -1003,9 +952,7 @@ public class DeviceAgentServiceTest {
operation.setPayLoad(null);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -1024,12 +971,9 @@ public class DeviceAgentServiceTest {
Operation operation = new Operation();
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Mockito.doThrow(new OperationManagementException()).when(this.deviceManagementProviderService)
.updateOperation(Mockito.any(), Mockito.any());
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -1050,7 +994,6 @@ public class DeviceAgentServiceTest {
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -1079,9 +1022,7 @@ public class DeviceAgentServiceTest {
operation.setPayLoad(null);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation);
Assert.assertNotNull(response, "The response should not be null");
@ -1104,9 +1045,8 @@ public class DeviceAgentServiceTest {
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(new ArrayList<String>() {});
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
Operation.Status.COMPLETED);
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER, Operation.Status.COMPLETED);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
@ -1116,14 +1056,11 @@ public class DeviceAgentServiceTest {
public void testGetOperationSuccess() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
Operation.Status.COMPLETED);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER, Operation.Status.COMPLETED);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200");
@ -1134,16 +1071,13 @@ public class DeviceAgentServiceTest {
OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getOperationsByDeviceAndStatus(Mockito.any(), Mockito.any()
)).thenThrow(new OperationManagementException());
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
Operation.Status.COMPLETED);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Mockito.when(this.deviceManagementProviderService.getOperationsByDeviceAndStatus(Mockito.any(), Mockito.any()))
.thenThrow(new OperationManagementException());
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER, Operation.Status.COMPLETED);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
@ -1154,13 +1088,12 @@ public class DeviceAgentServiceTest {
public void testGetOperationsWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
Operation.Status.COMPLETED);
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER, Operation.Status.COMPLETED);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");

@ -31,8 +31,10 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
@ -553,4 +555,51 @@ public class DeviceManagementServiceImplTest {
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Expects to return HTTP 500 when an exception occurred while getting effective policy of the device");
}
@Test(description = "Testing changing device status")
public void testChangeDeviceStatus() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService
.changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.INACTIVE);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
@Test(description = "Testing changing device status when device does not exist")
public void testChangeDeviceStatusWhenDeviceNotExists() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean())).thenReturn(null);
Response response = this.deviceManagementService
.changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.INACTIVE);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "Testing changing device status when device cannot be retrieved")
public void testChangeDeviceStatusException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean()))
.thenThrow(new DeviceManagementException());
Response response = this.deviceManagementService
.changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.ACTIVE);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "Testing changing device status when unable to change device status")
public void testChangeDeviceStatusWhenUnableToChangeStatus() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService
.changeDeviceStatus(Mockito.any(DeviceIdentifier.class), Mockito.any()))
.thenThrow(new DeviceManagementException());
Response response = this.deviceManagementService
.changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.ACTIVE);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
Mockito.reset(this.deviceManagementProviderService);
}
}

@ -83,24 +83,18 @@ public class DeviceTypeManagementAdminServiceTest {
public void testGetDeviceTypes() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceTypeManagementAdminService.getDeviceTypes();
log.info(response.getEntity());
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The Response status code " +
"should be 200.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The Response status code should be 200.");
}
@Test(description = "Test the error scenario of getting all the device types.")
public void testGetDeviceTypesError() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(deviceManagementProviderService.getDeviceTypes()).thenThrow(new DeviceManagementException());
Response response = this.deviceTypeManagementAdminService.getDeviceTypes();
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The expected status code is 500.");
@ -111,12 +105,8 @@ public class DeviceTypeManagementAdminServiceTest {
public void testAddDeviceTypeWithExistingName() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE_1, TEST_DEVICE_TYPE_ID_1);
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
log.info(response.getEntity());
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(),
"The Response Status code should be 409.");
@ -126,14 +116,9 @@ public class DeviceTypeManagementAdminServiceTest {
public void testAddDeviceTypeWithUnqualifiedName() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE_2, TEST_DEVICE_TYPE_ID_2);
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
log.info(response.getEntity());
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The Response Status code should be 400.");
@ -146,12 +131,9 @@ public class DeviceTypeManagementAdminServiceTest {
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService"))
.toReturn(this.deviceTypeGeneratorService);
Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The Response Status code should be 200.");
@ -162,11 +144,7 @@ public class DeviceTypeManagementAdminServiceTest {
public void testAddDeviceTypeWithNoDeviceType() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceTypeManagementAdminService.addDeviceType(null);
log.info(response.getEntity());
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The Response Status code should be 409.");
@ -178,10 +156,8 @@ public class DeviceTypeManagementAdminServiceTest {
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenThrow(new
DeviceManagementException());
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The Response Status code should be 500.");
@ -194,10 +170,8 @@ public class DeviceTypeManagementAdminServiceTest {
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService"))
.toReturn(this.deviceTypeGeneratorService);
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The Response Status code should be 200.");
@ -210,10 +184,8 @@ public class DeviceTypeManagementAdminServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService"))
.toReturn(this.deviceTypeGeneratorService);
Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The Response Status code should be 400.");
@ -224,9 +196,7 @@ public class DeviceTypeManagementAdminServiceTest {
public void testUpdateDeviceTypeWithNullDeviceType() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceTypeManagementAdminService.updateDeviceType(null);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The Response Status code should be 400.");
@ -237,13 +207,10 @@ public class DeviceTypeManagementAdminServiceTest {
public void testUpdateDeviceTypeWithException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString()))
.thenThrow(new DeviceManagementException());
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType);
Assert.assertNotNull(response, "The response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The Response Status code should be 500.");

@ -89,7 +89,6 @@ public class DeviceTypeManagementServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDeviceTypes()).thenThrow(new DeviceManagementException());
Response response = this.deviceTypeManagementService.getDeviceTypes();
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
@ -103,7 +102,6 @@ public class DeviceTypeManagementServiceTest {
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenThrow(new
DeviceManagementException());
Response response = this.deviceTypeManagementService.getDeviceTypes(MODIFIED_SINCE);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
@ -163,10 +161,8 @@ public class DeviceTypeManagementServiceTest {
public void testGetDeviceTypesWithDeviceTypes() throws Exception {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
List<DeviceType> deviceTypes = DeviceMgtAPITestHelper.getDummyDeviceTypeList(5);
Mockito.when(this.deviceManagementProviderService.getDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceTypeManagementService.getDeviceTypes();
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -189,7 +185,6 @@ public class DeviceTypeManagementServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(),
@ -203,7 +198,6 @@ public class DeviceTypeManagementServiceTest {
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString()))
.thenThrow(new DeviceManagementException());
Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
@ -227,10 +221,8 @@ public class DeviceTypeManagementServiceTest {
Method clearMetaEntryInfo = DeviceTypeManagementServiceImpl.class.getDeclaredMethod("clearMetaEntryInfo",
DeviceType.class);
clearMetaEntryInfo.setAccessible(true);
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
DeviceType returned = (DeviceType) clearMetaEntryInfo.invoke(this.deviceTypeManagementService, deviceType);
Assert.assertNotNull(returned.getDeviceTypeMetaDefinition(), "The response object is null.");
}
}

@ -0,0 +1,60 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
public class GeoLocationBasedServiceImplTest {
private DeviceManagementProviderService deviceManagementProviderService;
private PrivilegedCarbonContext context;
private GeoLocationBasedService geoLocationBasedService;
@BeforeClass
public void init() {
deviceManagementProviderService = Mockito.mock(DeviceManagementProviderService.class);
geoLocationBasedService = new GeoLocationBasedServiceImpl();
context = Mockito.mock(PrivilegedCarbonContext.class);
Mockito.doReturn("admin").when(context).getUsername();
}
@Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are no devices" +
"in the given map boundaries")
public void testGetGeoDeviceLocations1() throws DeviceManagementException {
Mockito.doReturn(new ArrayList<GeoCluster>()).when(deviceManagementProviderService)
.findGeoClusters(Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt());
Response response = geoLocationBasedService.getGeoDeviceLocations(0.4, 15, 75.6,
90.1, 6);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"getGeoDeviceLocations request failed with valid parameters");
}
@Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are devices" +
"in the given map boundaries")
public void testGetGeoDeviceLocations2() throws DeviceManagementException {
List<GeoCluster> geoClusters = new ArrayList<>();
geoClusters.add(new GeoCluster(new GeoCoordinate(1.5, 80.7),
new GeoCoordinate(1.1, 79.5), new GeoCoordinate(1.9, 82.1), 3,
"tb32", "aegtew234", "android"));
geoClusters.add(new GeoCluster(new GeoCoordinate(10.2, 86.1),
new GeoCoordinate(9.8, 84.7), new GeoCoordinate(11.1, 88.1), 4,
"t1gd", "swerty12s", "android"));
Mockito.doReturn(geoClusters).when(deviceManagementProviderService)
.findGeoClusters(Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt());
Response response = geoLocationBasedService.getGeoDeviceLocations(0.4, 15, 75.6,
90.1, 6);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"getGeoDeviceLocations request failed with valid parameters");
}
}

@ -21,7 +21,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -128,6 +128,16 @@ public interface DeviceManager {
*/
Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
/**
* Method to update device properties.
*
* @param deviceId identifier to identify the device
* @param list device properties list
* @return A boolean indicating the status of the operation.
* @throws DeviceManagementException If some unusual behaviour is observed while updating the device properties
*/
boolean updateDeviceProperties(DeviceIdentifier deviceId, List<Device.Property> list) throws DeviceManagementException;
/**
* Method to update device information.
*

@ -63,6 +63,16 @@ public interface NotificationManagementService {
boolean updateNotificationStatus(int notificationId, Notification.Status status) throws
NotificationManagementException;
/**
* Method for updating status all notifications.
*
* @return boolean status of the operation.
* @throws NotificationManagementException
* if something goes wrong while updating the Notification.
*/
boolean updateAllNotifications(Notification.Status status, int tenantID) throws
NotificationManagementException;
/**
* Method to fetch all the notifications in the database.
*

@ -96,6 +96,10 @@ public interface OperationManager {
List<Activity> getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException;
List<Activity> getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException;
int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException;
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException;
/**

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.192-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation;
import org.wso2.carbon.user.api.Permission;
public final class DeviceManagementConstants {
@ -99,4 +100,29 @@ public final class DeviceManagementConstants {
public static final int DEFAULT_BATCH_SIZE = 1000;
}
public static final class User {
private User() {
throw new AssertionError();
}
public static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user";
public static final String DEFAULT_DEVICE_ADMIN = "Internal/devicemgt-admin";
// Permissions that are given for a normal device user.
public static final Permission[] PERMISSIONS_FOR_DEVICE_USER = {
new Permission("/permission/admin/Login", "ui.execute"),
new Permission("/permission/admin/device-mgt/device/api/subscribe", "ui.execute"),
new Permission("/permission/admin/device-mgt/devices/enroll", "ui.execute"),
new Permission("/permission/admin/device-mgt/devices/disenroll", "ui.execute"),
new Permission("/permission/admin/device-mgt/devices/owning-device/view", "ui.execute"),
new Permission("/permission/admin/manage/portal", "ui.execute")
};
// Permissions that are given for a normal device admin.
public static final Permission[] PERMISSIONS_FOR_DEVICE_ADMIN = {
new Permission("/permission/admin/device-mgt", "ui.execute"),
new Permission("/permission/admin/manage/api", "ui.execute"),
new Permission("/permission/admin/manage/portal", "ui.execute")
};
}
}

@ -0,0 +1,49 @@
/*
* Copyright (c) 2017, 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.core.archival;
public class ArchivalException extends Exception {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ArchivalException(String message) {
super(message);
setErrorMessage(message);
}
public ArchivalException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
protected ArchivalException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
setErrorMessage(message);
}
}

@ -0,0 +1,26 @@
/*
* Copyright (c) 2017, 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.core.archival;
public interface ArchivalService {
void archiveTransactionalRecords() throws ArchivalException;
void deleteArchivedRecords() throws ArchivalException;
}

@ -0,0 +1,220 @@
/*
* Copyright (c) 2017, 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.core.archival;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.archival.dao.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ArchivalServiceImpl implements ArchivalService {
private static Log log = LogFactory.getLog(ArchivalServiceImpl.class);
private ArchivalDAO archivalDAO;
private DataDeletionDAO dataDeletionDAO;
private static int ITERATION_COUNT = 10000;
private String[] NOT_IN_PROGRESS_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED"};
private String[] NOT_PENDING_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED", "IN_PROGRESS"};
private String[] NOT_PENDING_IN_PROGRESS_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED"};
public ArchivalServiceImpl() {
this.archivalDAO = ArchivalSourceDAOFactory.getDataPurgingDAO();
this.dataDeletionDAO = ArchivalDestinationDAOFactory.getDataDeletionDAO();
}
@Override
public void archiveTransactionalRecords() throws ArchivalException {
try {
ArchivalSourceDAOFactory.openConnection();
ArchivalDestinationDAOFactory.openConnection();
List<Integer> allOperations = archivalDAO.getAllOperations();
List<Integer> pendingAndIPOperations = archivalDAO.getPendingAndInProgressOperations();
log.info(allOperations.size() + " All Operations. " + pendingAndIPOperations.size() +
" P&IP Operations");
//Get the diff of operations
Set<Integer> setA = new HashSet<>(allOperations);
Set<Integer> setB = new HashSet<>(pendingAndIPOperations);
setA.removeAll(setB);
List<Integer> candidates = new ArrayList<>();
candidates.addAll(setA);
int total = candidates.size();
int batches = calculateNumberOfBatches(total);
int batchSize = ITERATION_COUNT;
if (log.isDebugEnabled()) {
log.debug(total + " Operations ready for archiving. " + batches + " iterations to be done.");
}
beginTransactions();
for (int i = 1; i <= batches; i++) {
int startIdx = batchSize * (i - 1);
int endIdx = batchSize * i;
if (i == batches) {
endIdx = startIdx + (total % batchSize);
}
if(log.isDebugEnabled()) {
log.debug("\n\n############ Iterating over batch " + i + "[" +
startIdx + "," + endIdx + "] #######");
}
List<Integer> subList = candidates.subList(startIdx, endIdx);
prepareTempTable(subList);
//Purge the largest table, DM_DEVICE_OPERATION_RESPONSE
if (log.isDebugEnabled()) {
log.debug("## Purging operation responses");
}
archivalDAO.moveOperationResponses();
//Purge the notifications table, DM_NOTIFICATION
if (log.isDebugEnabled()) {
log.debug("## Purging notifications");
}
archivalDAO.moveNotifications();
//Purge the command operations table, DM_COMMAND_OPERATION
if (log.isDebugEnabled()) {
log.debug("## Purging command operations");
}
archivalDAO.moveCommandOperations();
//Purge the profile operation table, DM_PROFILE_OPERATION
if (log.isDebugEnabled()) {
log.debug("## Purging profile operations");
}
archivalDAO.moveProfileOperations();
//Purge the enrolment mappings table, DM_ENROLMENT_OP_MAPPING
if (log.isDebugEnabled()) {
log.debug("## Purging enrolment mappings");
}
archivalDAO.moveEnrolmentMappings();
//Finally, purge the operations table, DM_OPERATION
if (log.isDebugEnabled()) {
log.debug("## Purging operations");
}
archivalDAO.moveOperations();
}
commitTransactions();
} catch (ArchivalDAOException e) {
rollbackTransactions();
throw new ArchivalException("An error occurred while data archival", e);
} catch (SQLException e) {
throw new ArchivalException("An error occurred while connecting to the archival database.", e);
} finally {
ArchivalSourceDAOFactory.closeConnection();
ArchivalDestinationDAOFactory.closeConnection();
}
}
private void prepareTempTable(List<Integer> subList) throws ArchivalDAOException {
//Clean up the DM_ARCHIVED_OPERATIONS table
if (log.isDebugEnabled()) {
log.debug("## Truncating the temporary table");
}
archivalDAO.truncateOperationIDsForArchival();
archivalDAO.copyOperationIDsForArchival(subList);
}
private void beginTransactions() throws ArchivalException {
try {
ArchivalSourceDAOFactory.beginTransaction();
ArchivalDestinationDAOFactory.beginTransaction();
} catch (TransactionManagementException e) {
log.error("An error occurred during starting transactions", e);
throw new ArchivalException("An error occurred during starting transactions", e);
}
}
private void commitTransactions() {
ArchivalSourceDAOFactory.commitTransaction();
ArchivalDestinationDAOFactory.commitTransaction();
}
private void rollbackTransactions() {
ArchivalSourceDAOFactory.rollbackTransaction();
ArchivalDestinationDAOFactory.rollbackTransaction();
}
private int calculateNumberOfBatches(int total) {
int batches = 0;
int batchSize = ITERATION_COUNT;
if ((total % batchSize) > 0) {
batches = (total / batchSize) + 1;
} else {
batches = total / batchSize;
}
return batches;
}
@Override
public void deleteArchivedRecords() throws ArchivalException {
try {
ArchivalDestinationDAOFactory.openConnection();
if (log.isDebugEnabled()) {
log.debug("## Deleting operation responses");
}
dataDeletionDAO.deleteOperationResponses();
if (log.isDebugEnabled()) {
log.debug("## Deleting notifications ");
}
dataDeletionDAO.deleteNotifications();
if (log.isDebugEnabled()) {
log.debug("## Deleting command operations");
}
dataDeletionDAO.deleteCommandOperations();
if (log.isDebugEnabled()) {
log.debug("## Deleting profile operations ");
}
dataDeletionDAO.deleteProfileOperations();
if (log.isDebugEnabled()) {
log.debug("## Deleting enrolment mappings ");
}
dataDeletionDAO.deleteEnrolmentMappings();
if (log.isDebugEnabled()) {
log.debug("## Deleting operations ");
}
dataDeletionDAO.deleteOperations();
} catch (SQLException e) {
throw new ArchivalException("An error occurred while initialising data source for archival", e);
} catch (ArchivalDAOException e) {
log.error("An error occurred while executing DataDeletionTask");
} finally {
ArchivalDestinationDAOFactory.closeConnection();
}
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2017, 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.core.archival.dao;
import java.util.List;
/**
* Operations to move data from DM database to archival database
*/
public interface ArchivalDAO {
int DEFAULT_BATCH_SIZE = 1000;
List<Integer> getAllOperations() throws ArchivalDAOException;
List<Integer> getPendingAndInProgressOperations() throws ArchivalDAOException;
void copyOperationIDsForArchival(List<Integer> operationIds) throws ArchivalDAOException;
void moveOperationResponses() throws ArchivalDAOException;
void moveNotifications() throws ArchivalDAOException;
void moveCommandOperations() throws ArchivalDAOException;
void moveProfileOperations() throws ArchivalDAOException;
void moveEnrolmentMappings() throws ArchivalDAOException;
void moveOperations() throws ArchivalDAOException;
void truncateOperationIDsForArchival() throws ArchivalDAOException;
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2017, 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.core.archival.dao;
public class ArchivalDAOException extends Exception {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ArchivalDAOException(String message) {
super(message);
setErrorMessage(message);
}
public ArchivalDAOException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
protected ArchivalDAOException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
setErrorMessage(message);
}
}

@ -0,0 +1,60 @@
/*
* Copyright (c) 2017, 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.core.archival.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ArchivalDAOUtil {
private static final Log log = LogFactory.getLog(ArchivalDAOUtil.class);
public static void cleanupResources(Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing the result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing the statement", e);
}
}
}
public static void cleanupResources(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing the statement", e);
}
}
}
}

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

Loading…
Cancel
Save