add certificateMgtService

merge-requests/7/head
hasuniea 9 years ago
commit 57d445237a

@ -31,7 +31,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - Mobile Device Management API</name>
<name>WSO2 Carbon - Certificate Management API</name>
<description>WSO2 Carbon - Certificate Management API</description>
<url>http://wso2.org</url>

@ -13,7 +13,7 @@ public interface CertificateMgtService {
* @return X509Certificate type sign certificate.
*/
@POST
@Path("csr-sign")
@Path("signcsr")
@Produces({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN})
Response getSignedCertFromCSR(String binarySecurityToken);

@ -8,10 +8,7 @@ import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator;
import org.wso2.carbon.certificate.mgt.jaxrs.api.CertificateMgtService;
import org.wso2.carbon.certificate.mgt.jaxrs.exception.Message;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.security.cert.CertificateEncodingException;

@ -0,0 +1,209 @@
<?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.
-->
<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>1.1.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.cert.admin.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - Admin Certificate Management API</name>
<description>WSO2 Carbon - Admin Certificate Management API</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>admin-certificate</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</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="admin-certificate.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.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.neethi.wso2</groupId>
<artifactId>neethi</artifactId>
</exclusion>
</exclusions>
</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.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,123 @@
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public interface Certificate {
/**
* Save a list of certificates and relevant information in the database.
*
* @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as
* a pem and a serial number.
* @return Status of the data persist operation.
*/
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "POST",
value = "Adding an SSL Certificate",
notes = "Add a new SSL certificate to the client end database")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Added successfully"),
@ApiResponse(code = 500, message = "Error occurred while saving the certificate")
})
@Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"})
Response saveCertificate(@HeaderParam("Accept") String acceptHeader,
@ApiParam(name = "enrollmentCertificates", value = "certificate with serial, "
+ "pem and tenant id", required = true) EnrollmentCertificate[]
enrollmentCertificates);
/**
* Get a certificate when the serial number is given.
*
* @param serialNumber serial of the certificate needed.
* @return certificate response.
*/
@GET
@Path("{serialNumber}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting Details of an SSL Certificate",
notes = "Get the client side SSL certificate details",
response = CertificateResponse.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = CertificateResponse.class),
@ApiResponse(code = 400, message = "Notification status updated successfully"),
@ApiResponse(code = 500, message = "Error occurred while converting PEM file to X509Certificate")
})
@Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"})
Response getCertificate(@HeaderParam("Accept") String acceptHeader,
@ApiParam(name = "serialNumber", value = "Provide the serial number of the "
+ "certificate that you wish to get the details of", required = true)
@PathParam("serialNumber") String serialNumber);
/**
* Get all certificates in a paginated manner.
*
* @param startIndex index of the first record to be fetched
* @param length number of records to be fetched starting from the start index.
* @return paginated result of certificate.
* @throws MDMAPIException
*/
@GET
@Path("paginate")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "GET",
value = "Getting the Certificate Details in a Paginated Manner",
notes = "You will have many certificates used for mutual SSL. In a situation where you wish to "
+ "view all the certificate details, it is not feasible to show all the details on one "
+ "page therefore the details are paginated",
response = PaginationResult.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = PaginationResult.class),
@ApiResponse(code = 400, message = "Invalid start index"),
@ApiResponse(code = 400, message = "Invalid length value"),
@ApiResponse(code = 500, message = "Error occurred while fetching all certificates")
})
@Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"})
Response getAllCertificates(@HeaderParam("Accept") String acceptHeader,
@ApiParam(name = "start",
value = "Provide the starting pagination index as the value", required = true)
@QueryParam("start") int startIndex,
@ApiParam(name = "length", value = "Provide how many certificate details you"
+ " require from the starting pagination index as the value",
required = true) @QueryParam("length") int length) throws MDMAPIException;
@DELETE
@Path("{serialNumber}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML,
httpMethod = "DELETE",
value = "Deleting an SSL Certificate",
notes = "Delete an SSL certificate that's on the client end",
response = boolean.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 400, message = "Invalid start index"),
@ApiResponse(code = 500, message = "Error when deleting the certificate"
) })
@Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"})
Response removeCertificate(@HeaderParam("Accept") String acceptHeader,
@ApiParam(name = "serialNumber", value = "Provide the serial number of the "
+ "certificate that you wish to delete", required = true)
@PathParam("serialNumber") String serialNumber) throws MDMAPIException;
}

@ -0,0 +1,34 @@
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
/**
* Created by hasunie on 5/26/16.
*/
public class EnrollmentCertificate {
String serial;
String pem;
int tenantId;
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public String getPem() {
return pem;
}
public void setPem(String pem) {
this.pem = pem;
}
}

@ -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,95 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@Provider
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public class GsonMessageBodyHandler implements MessageBodyWriter<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 {
Type jsonType = null;
if (type.equals(type)) {
jsonType = type;
}
getGson().toJson(object, jsonType, 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,181 @@
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.Certificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.exception.Message;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
public class CertificateImpl implements Certificate {
private static Log log = LogFactory.getLog(CertificateImpl.class);
/**
* Save a list of certificates and relevant information in the database.
*
* @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as
* a pem and a serial number.
* @return Status of the data persist operation.
*/
@POST
public Response saveCertificate(@HeaderParam("Accept") String acceptHeader,
EnrollmentCertificate[] enrollmentCertificates) {
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
CertificateManagementService certificateService;
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate;
certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
try {
for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) {
certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
certificate.setSerial(enrollmentCertificate.getSerial());
certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem()));
certificates.add(certificate);
}
certificateService.saveCertificate(certificates);
return Response.status(Response.Status.CREATED).entity("Added successfully.").
type(responseMediaType).build();
} catch (KeystoreException e) {
String msg = "Error occurred while converting PEM file to X509Certificate.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
}
}
/**
* Get a certificate when the serial number is given.
*
* @param serialNumber serial of the certificate needed.
* @return certificate response.
*/
@GET
@Path("{serialNumber}")
public Response getCertificate(@HeaderParam("Accept") String acceptHeader,
@PathParam("serialNumber") String serialNumber) {
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
Message message = new Message();
if (serialNumber == null || serialNumber.isEmpty()) {
message.setErrorMessage("Invalid serial number");
message.setDiscription("Serial number is missing or invalid.");
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
}
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
List<CertificateResponse> certificateResponse;
try {
certificateResponse = certificateService.searchCertificates(serialNumber);
return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build();
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
}
}
/**
* Get all certificates in a paginated manner.
*
* @param startIndex index of the first record to be fetched
* @param length number of records to be fetched starting from the start index.
* @return paginated result of certificate.
* @throws MDMAPIException
*/
@GET
@Path("paginate")
public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader,
@QueryParam("start") int startIndex,
@QueryParam("length") int length)
throws MDMAPIException {
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
Message message = new Message();
if (startIndex < 0) {
message.setErrorMessage("Invalid start index.");
message.setDiscription("Start index cannot be less that 0.");
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
} else if (length <= 0) {
message.setErrorMessage("Invalid length value.");
message.setDiscription("Length should be a positive integer.");
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
}
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
PaginationRequest paginationRequest = new PaginationRequest(startIndex, length);
try {
PaginationResult certificates = certificateService.getAllCertificates(paginationRequest);
return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build();
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while fetching all certificates.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
}
}
/**
* Get all certificates
*
* @return certificate details in an array.
* @throws MDMAPIException
*/
@GET
public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader)
throws MDMAPIException {
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
try {
List<CertificateResponse> certificates = certificateService.getCertificates();
return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build();
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while fetching all certificates.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
@DELETE
@Path("{serialNumber}")
public Response removeCertificate(@HeaderParam("Accept") String acceptHeader,
@PathParam("serialNumber") String serialNumber) throws MDMAPIException {
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
Message message = new Message();
if (serialNumber == null || serialNumber.isEmpty()) {
message.setErrorMessage("Invalid serial number");
message.setDiscription("Serial number is missing or invalid.");
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
}
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
boolean deleted;
try {
deleted = certificateService.removeCertificate(serialNumber);
if(deleted){
return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build();
} else {
return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build();
}
} catch (CertificateManagementDAOException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
}
}
}

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

@ -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,67 @@
<?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/emm-admin/certificate/GetSignCSR</path>
<url>/certificates/signcsr</url>
<method>POST</method>
<scope>emm_admin</scope>
</Permission>
<!-- Certificate related APIs -->
<Permission>
<name>Save certificate in the database</name>
<path>/device-mgt/admin/certificate/save</path>
<url>/certificates</url>
<method>POST</method>
</Permission>
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/admin/certificate/Get</path>
<url>/certificates/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/admin/certificate/GetAll</path>
<url>/certificates</url>
<method>GET</method>
</Permission>
<Permission>
<name>get certificate in the database</name>
<path>/device-mgt/admin/certificate/Get</path>
<url>/certificates/*</url>
<method>DELETE</method>
</Permission>
<!-- End of Certificate 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,66 @@
<?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.
-->
<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.cert.jaxrs.api"/>
<property name="version" value="1.0.0"/>
<property name="host" value="localhost:9443"/>
<property name="basePath" value="/"/>
<property name="title" value="Device Management Admin Service API Definitions"/>
<property name="contact" value="dev@wso2.org"/>
<property name="license" value="Apache 2.0"/>
<property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<property name="scan" value="true"/>
</bean>
<bean id="certificateServiceBean" class="org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl.CertificateImpl"/>
<bean id="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,66 @@
<?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>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</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>
<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>
</web-app>

@ -55,7 +55,11 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
try {
conn = this.getConnection();
stmt = conn.prepareStatement(
"INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID) VALUES (?,?,?)");
"INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME)"
+ " VALUES (?,?,?,?)");
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.
getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
for (Certificate certificate : certificates) {
String serialNumber = certificate.getSerial();
if (serialNumber == null || serialNumber.isEmpty()) {
@ -67,6 +71,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
stmt.setString(1, serialNumber);
stmt.setObject(2, byteArrayInputStream);
stmt.setInt(3, certificate.getTenantId());
stmt.setString(4, username);
stmt.addBatch();
}
stmt.executeBatch();
@ -89,8 +94,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
try {
conn = this.getConnection();
String query =
"SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" +
" AND TENANT_ID = ? ";
"SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM"
+ " DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ? AND TENANT_ID = ? ";
stmt = conn.prepareStatement(query);
stmt.setString(1, serialNumber);
stmt.setInt(2, tenantId);
@ -102,6 +107,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
certificateResponse.setCertificate(certificateBytes);
certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
break;
}
@ -128,8 +134,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
try {
conn = this.getConnection();
String query =
"SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER LIKE ?" +
" AND TENANT_ID = ? ";
"SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM DM_DEVICE_CERTIFICATE "
+ "WHERE SERIAL_NUMBER LIKE ? AND TENANT_ID = ? ";
stmt = conn.prepareStatement(query);
stmt.setString(1, "%" + serialNumber + "%");
stmt.setInt(2, tenantId);
@ -140,6 +146,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
byte [] certificateBytes = resultSet.getBytes("CERTIFICATE");
certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse);
}
@ -164,8 +171,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? " +
"ORDER BY ID DESC LIMIT ?,?";
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM "
+ "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setInt(2, request.getStartIndex());
@ -178,6 +185,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
byte [] certificateBytes = resultSet.getBytes("CERTIFICATE");
certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse);
resultCount++;
@ -204,8 +212,8 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? " +
"ORDER BY ID DESC";
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME"
+ " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery();
@ -215,6 +223,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO {
byte [] certificateBytes = resultSet.getBytes("CERTIFICATE");
certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse);
}

@ -56,6 +56,17 @@ public class CertificateResponse {
@ApiModelProperty(name = "certificateVersion", value = "The version of the certificate", required = true)
int certificateVersion;
@ApiModelProperty(name ="username", value="username of the logged user", required = true)
String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getNotAfter() {
return notAfter;
}

@ -37,6 +37,7 @@
<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>
</modules>
<build>

@ -22,8 +22,8 @@ public final class GadgetDataServiceDAOConstants {
public static class DatabaseView {
public static final String DEVICES_VIEW_1 = "DEVICES_WITH_POLICY_COMPLIANCE_STATUS";
public static final String DEVICES_VIEW_2 = "DEVICES_WITH_NON_COMPLIANT_FEATURES";
public static final String DEVICES_VIEW_1 = "POLICY_COMPLIANCE_INFO";
public static final String DEVICES_VIEW_2 = "FEATURE_NON_COMPLIANCE_INFO";
private DatabaseView() {
throw new AssertionError();

@ -19,6 +19,9 @@
package org.wso2.carbon.device.mgt.core.search.mgt.impl;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
@ -191,7 +194,6 @@ public class ProcessorImpl implements Processor {
}
return maps;
}
private void setApplicationListOfDevices(List<DeviceWrapper> deviceWrappers) throws SearchMgtException {
try {
DeviceManagementDAOFactory.openConnection();

@ -129,10 +129,9 @@ public class CertificateAuthenticator implements WebappAuthenticator {
isEmpty()) {
authenticationInfo.setTenantId(certificateResponse.getTenantId());
authenticationInfo.setStatus(Status.CONTINUE);
authenticationInfo.setUsername(certificateResponse.getCommonName());
authenticationInfo.setUsername(certificateResponse.getUsername());
try {
authenticationInfo.setTenantDomain(Utils.
getTenantDomain(
authenticationInfo.setTenantDomain(Utils.getTenantDomain(
certificateResponse.getTenantId()));
} catch (AuthenticationException e) {
authenticationInfo.setStatus(Status.FAILURE);

@ -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.
-->
<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>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt-feature</artifactId>
<version>1.1.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.cert.admin.api.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - Admin Certificate Management API Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the APIs required for Admin Certificate Management.</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.cert.admin.api
</artifactId>
<version>${project.version}</version>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps
</outputDirectory>
<destFileName>admin-certificate.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.certificate.mgt.cert.admin.api</id>
<propertiesFile>../../../features/etc/feature.properties
</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server
</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false
</propertyDef>
</properties>
</adviceFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,2 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/admin-certificate.war,target:${installFolder}/../../deployment/server/webapps/admin-certificate.war,overwrite:true);\

@ -37,6 +37,7 @@
<modules>
<module>org.wso2.carbon.certificate.mgt.server.feature</module>
<module>org.wso2.carbon.certificate.mgt.api.feature</module>
<module>org.wso2.carbon.certificate.mgt.cert.admin.api.feature</module>
</modules>
</project>

@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);
@ -515,7 +516,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
-- DASHBOARD RELATED VIEWS --
CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS
CREATE VIEW POLICY_COMPLIANCE_INFO AS
SELECT
DEVICE_INFO.DEVICE_ID,
DEVICE_INFO.DEVICE_IDENTIFICATION,
@ -544,7 +545,7 @@ FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
ORDER BY DEVICE_INFO.DEVICE_ID;
CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS
CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS
SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE.DEVICE_IDENTIFICATION,

@ -22,6 +22,7 @@ CREATE TABLE DM_DEVICE_CERTIFICATE (
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE VARBINARY(max) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);
@ -507,7 +508,7 @@ CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC)
-- DASHBOARD RELATED VIEWS --
CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS
CREATE VIEW POLICY_COMPLIANCE_INFO AS
SELECT TOP 100 PERCENT
DEVICE_INFO.DEVICE_ID,
DEVICE_INFO.DEVICE_IDENTIFICATION,
@ -539,7 +540,7 @@ ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
ORDER BY DEVICE_INFO.DEVICE_ID;
GO
CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS
CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS
SELECT TOP 100 PERCENT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE.DEVICE_IDENTIFICATION,

@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
)ENGINE = InnoDB;
@ -545,7 +546,7 @@ POLICY_ID,
STATUS AS IS_COMPLIANT
FROM DM_POLICY_COMPLIANCE_STATUS;
CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS
CREATE VIEW POLICY_COMPLIANCE_INFO AS
SELECT
DEVICE_INFO_VIEW.DEVICE_ID,
DEVICE_INFO_VIEW.DEVICE_IDENTIFICATION,
@ -562,7 +563,7 @@ DEVICE_WITH_POLICY_INFO_VIEW
ON DEVICE_INFO_VIEW.DEVICE_ID = DEVICE_WITH_POLICY_INFO_VIEW.DEVICE_ID
ORDER BY DEVICE_INFO_VIEW.DEVICE_ID;
CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS
CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS
SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE.DEVICE_IDENTIFICATION,

@ -50,6 +50,7 @@ CREATE TABLE DM_DEVICE_CERTIFICATE (
SERIAL_NUMBER VARCHAR2(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID NUMBER(10) DEFAULT 0,
USERNAME VARCHAR2(500) DEFAULT NULL,
PRIMARY KEY (ID)
)
/

@ -9,7 +9,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID BIGSERIAL NOT NULL PRIMARY KEY,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BYTEA DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS DM_DEVICE (
@ -434,7 +435,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
-- DASHBOARD RELATED VIEWS --
CREATE VIEW DEVICES_WITH_POLICY_COMPLIANCE_STATUS AS
CREATE VIEW POLICY_COMPLIANCE_INFO AS
SELECT
DEVICE_INFO.DEVICE_ID,
DEVICE_INFO.DEVICE_IDENTIFICATION,
@ -463,7 +464,7 @@ FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
ORDER BY DEVICE_INFO.DEVICE_ID;
CREATE VIEW DEVICES_WITH_NON_COMPLIANT_FEATURES AS
CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS
SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE.DEVICE_IDENTIFICATION,

@ -52,7 +52,7 @@
<module>features/oauth-extensions</module>
<module>features/email-sender</module>
<module>features/jwt-client</module>
<module>features/device-mgt-extensions</module>
<module>features/device-mgt-extensions</module>
</modules>
<dependencyManagement>
@ -1727,7 +1727,6 @@
</repository>
</repositories>
<properties>
<testng.version>6.1.1</testng.version>
<carbon.kernel.version>4.4.3</carbon.kernel.version>

Loading…
Cancel
Save