Fix Certificate test case and delete and search option

remotes/1729253769841084517/master
Nishan Sangeeth 1 year ago committed by navodzoysa
parent 7afe7fca08
commit 017c70fa08

@ -247,14 +247,15 @@ public interface CertificateManagementAdminService {
* *
* @return paginated result of certificate. * @return paginated result of certificate.
*/ */
@GET @GET
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Getting Details of Certificates", value = "Getting Details of search Certificates",
notes = "Get all the details of the certificates you have used for mutual SSL. In a situation where you wish to " notes = "Get all the details of the search 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 " + "view all the search certificate details, it is not feasible to show all the details on one "
+ "page. Therefore, the details are paginated.", + "page. Therefore, the details are paginated.",
tags = "Certificate Management", tags = "Certificate Management",
extensions = { extensions = {
@ -308,24 +309,42 @@ public interface CertificateManagementAdminService {
}) })
Response getAllCertificates( Response getAllCertificates(
@ApiParam( @ApiParam(
name = "offset", name = "serialNumber",
value = "The starting pagination index for the complete list of qualified items.", value = "The serial number of the certificates",
required = false, required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") int offset, @QueryParam("serialNumber") String serialNumber,
@ApiParam( @ApiParam(
name = "limit", name = "deviceIdentifier",
value = "Provide how many certificate details you require from the starting pagination index/offset.", value = "The device identifier of the certificates",
required = false, required = false,
defaultValue = "5") defaultValue = "0")
@QueryParam("limit") int limit, @QueryParam("deviceIdentifier") String deviceIdentifier,
@ApiParam(
name = "username",
value = "User name of the certificate added user" ,
required = false,
defaultValue = "0")
@QueryParam("username") String username,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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" + "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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince); @HeaderParam("If-Modified-Since") String ifModifiedSince,
@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);
@DELETE @DELETE
@ApiOperation( @ApiOperation(

@ -18,7 +18,6 @@
package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.impl; package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.impl;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam; import javax.ws.rs.HeaderParam;
@ -26,7 +25,8 @@ import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.CertificateManagementAdminService; import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.CertificateManagementAdminService;
@ -84,6 +84,13 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
certificate.setSerial(enrollmentCertificate.getSerial()); certificate.setSerial(enrollmentCertificate.getSerial());
certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem()));
CertificateResponse existingCertificate = certificateService.getCertificateBySerial(enrollmentCertificate.getSerial());
if (existingCertificate != null) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Certificate with serial number " + enrollmentCertificate.getSerial() + " already exists.")
.build();
}
certificates.add(certificate); certificates.add(certificate);
} }
certificateService.saveCertificate(certificates); certificateService.saveCertificate(certificates);
@ -131,13 +138,24 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
*/ */
@GET @GET
public Response getAllCertificates( public Response getAllCertificates(
@QueryParam("offset") int offset, @QueryParam("serialNumber") String serialNumber, @QueryParam("deviceIdentifier") String deviceIdentifier,
@QueryParam("limit") int limit, @QueryParam("username") String username, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset,
@HeaderParam("If-Modified-Since") String ifModifiedSince) { @QueryParam("limit") int limit) {
RequestValidationUtil.validatePaginationInfo(offset, limit); RequestValidationUtil.validatePaginationInfo(offset, limit);
CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService();
CertificatePaginationRequest request = new CertificatePaginationRequest(offset, limit);
if (serialNumber != null && !serialNumber.isEmpty()) {
request.setSerialNumber(serialNumber);
}
if (deviceIdentifier != null){
request.setDeviceIdentifier(deviceIdentifier);
}
if (username != null){
request.setUsername(username);
}
try { try {
PaginationResult result = certificateService.getAllCertificates(offset, limit); PaginationResult result = certificateService.getAllCertificates(request);
CertificateList certificates = new CertificateList(); CertificateList certificates = new CertificateList();
certificates.setCount(result.getRecordsTotal()); certificates.setCount(result.getRecordsTotal());
certificates.setList((List<CertificateResponse>) result.getData()); certificates.setList((List<CertificateResponse>) result.getData());
@ -151,20 +169,34 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
} }
@DELETE @DELETE
public Response removeCertificate(@QueryParam("certificateId") String certificateId) { public Response removeCertificate(@QueryParam("serialNumber") String serialNumber) {
RequestValidationUtil.validateCertificateId(certificateId); RequestValidationUtil.validateSerialNumber(serialNumber);
CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService();
try { try {
boolean status = certificateService.removeCertificate(certificateId); boolean decision = certificateService.getValidateMetaValue();
if (decision) {
try {
boolean status = certificateService.removeCertificate(serialNumber);
if (!status) { if (!status) {
return Response.status(Response.Status.NOT_FOUND).entity( return Response.status(Response.Status.NOT_FOUND).entity(
"No certificate is found with the given " + "No certificate is found with the given " +
"certificate id '" + certificateId + "'").build(); "serial number '" + serialNumber + "'").build();
} else { } else {
return Response.status(Response.Status.OK).entity( return Response.status(Response.Status.OK).entity(
"Certificate that carries the certificate id '" + "Certificate that carries the serial number '" +
certificateId + "' has been removed").build(); 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();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity(
"User not have to access delete certificate " +
"serial number '" + serialNumber + "'").build();
} }
} catch (CertificateManagementException e) { } catch (CertificateManagementException e) {
String msg = "Error occurred while converting PEM file to X509Certificate"; String msg = "Error occurred while converting PEM file to X509Certificate";

@ -30,14 +30,6 @@ public class RequestValidationUtil {
} }
} }
public static void validateCertificateId(String certificateId) {
if (certificateId == null || certificateId.isEmpty()) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Certificate Id cannot be null or empty").build());
}
}
public static void validatePaginationInfo(int offset, int limit) { public static void validatePaginationInfo(int offset, int limit) {
if (offset < 0) { if (offset < 0) {
throw new InputValidationException( throw new InputValidationException(

@ -95,7 +95,8 @@
io.entgra.device.mgt.core.device.mgt.core.*, io.entgra.device.mgt.core.device.mgt.core.*,
org.wso2.carbon.registry.indexing.*, org.wso2.carbon.registry.indexing.*,
javax.cache.*, javax.cache.*,
javax.naming.ldap javax.naming.ldap,
com.google.gson.*
<!--org.bouncycastle.pkcs.jcajce--> <!--org.bouncycastle.pkcs.jcajce-->
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
@ -253,6 +254,10 @@
<artifactId>slf4j-simple</artifactId> <artifactId>slf4j-simple</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -18,8 +18,10 @@
package io.entgra.device.mgt.core.certificate.mgt.core.dao; package io.entgra.device.mgt.core.certificate.mgt.core.dao;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException;
import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult;
import java.util.List; import java.util.List;
@ -75,13 +77,12 @@ public interface CertificateDAO {
/** /**
* Get all the certificates in a paginated manner. * Get all the certificates in a paginated manner.
* *
* @param rowNum Stating index of the paginated result. * @param request index of the paginated result.
* @param limit Number of records to return.
* @return Pagination result with data and the count of results. * @return Pagination result with data and the count of results.
* @throws CertificateManagementDAOException * @throws CertificateManagementDAOException
* *
*/ */
PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException; PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException;
/** /**
* Get all the certificates. * Get all the certificates.
@ -95,10 +96,10 @@ public interface CertificateDAO {
/** /**
* Delete a certificate identified by a serial number() * Delete a certificate identified by a serial number()
* *
* @param certificateId number * @param serialNumber number
* @return whether the certificate was removed or not. * @return whether the certificate was removed or not.
*/ */
boolean removeCertificate(String certificateId) throws CertificateManagementDAOException; boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException;
List<CertificateResponse> searchCertificate(String serialNumber) throws CertificateManagementDAOException; List<CertificateResponse> searchCertificate(String serialNumber) throws CertificateManagementDAOException;

@ -237,7 +237,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME" String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME"
+ " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC"; + " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
@ -247,8 +247,6 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{
certificateResponse = new CertificateResponse(); certificateResponse = new CertificateResponse();
byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
certificateResponse.setCertificateId(resultSet.getString("ID"));
certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER"));
certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
certificateResponse.setUsername(resultSet.getString("USERNAME")); certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
@ -265,7 +263,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{
} }
@Override @Override
public boolean removeCertificate(String certificateId) throws CertificateManagementDAOException { public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -273,15 +271,15 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = String query =
"DELETE FROM DM_DEVICE_CERTIFICATE WHERE ID = ?" + "DELETE FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" +
" AND TENANT_ID = ? "; " AND TENANT_ID = ? ";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setString(1, certificateId); stmt.setString(1, serialNumber);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
return stmt.executeUpdate() > 0; return stmt.executeUpdate() > 0;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Unable to get the read the certificate with certificate id" + certificateId; String msg = "Unable to get the read the certificate with serialNumber" + serialNumber;
log.error(msg, e); log.error(msg, e);
throw new CertificateManagementDAOException(msg, e); throw new CertificateManagementDAOException(msg, e);
} finally { } finally {

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -47,47 +48,120 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl {
private Connection getConnection() throws SQLException { private Connection getConnection() throws SQLException {
return CertificateManagementDAOFactory.getConnection(); return CertificateManagementDAOFactory.getConnection();
} }
private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException {
private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int certificateCount = 0; int certificateCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?");
"SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) { if (serialNumber != null && !serialNumber.isEmpty()) {
queryBuilder.append(" AND SERIAL_NUMBER = ?");
}
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
queryBuilder.append(" AND DEVICE_IDENTIFIER = ?");
}
if (username != null && !username.isEmpty()) {
queryBuilder.append(" AND USERNAME LIKE ?");
}
String sql = queryBuilder.toString();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { int paramIdx = 2;
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setString(paramIdx++, serialNumber);
} }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
stmt.setString(paramIdx++, deviceIdentifier);
} }
if (username != null && !username.isEmpty()) {
stmt.setString(paramIdx, "%" + username + "%");
}
rs = stmt.executeQuery();
if (rs.next()) {
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT");
} }
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificate count.";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new CertificateManagementDAOException(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e);
} finally {
CertificateManagementDAOUtil.cleanupResources(stmt, rs);
} }
return certificateCount; return certificateCount;
} }
@Override @Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
CertificateResponse certificateResponse; CertificateResponse certificateResponse;
List<CertificateResponse> certificates = new ArrayList<>(); List<CertificateResponse> certificates = new ArrayList<>();
PaginationResult paginationResult; PaginationResult paginationResult;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
boolean isCertificateSerialNumberProvided = false;
boolean isCertificateDeviceIdentifierProvided = false;
boolean isCertificateUsernameProvided = false;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " String query = "SELECT * " +
+ "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; "FROM DM_DEVICE_CERTIFICATE " +
stmt = conn.prepareStatement(sql); "WHERE TENANT_ID = ? ";
stmt.setInt(1, tenantId); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setInt(2, rowNum); query += "AND SERIAL_NUMBER = ? ";
stmt.setInt(3, limit); isCertificateSerialNumberProvided = true;
resultSet = stmt.executeQuery(); }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
query += "AND DEVICE_IDENTIFIER = ? ";
isCertificateDeviceIdentifierProvided = true;
}
if (username != null && !username.isEmpty()) {
query += "AND USERNAME LIKE ? ";
isCertificateUsernameProvided = true;
}
query += "ORDER BY ID LIMIT ?,?";
int resultCount = 0; stmt = conn.prepareStatement(query);
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
if (isCertificateSerialNumberProvided) {
stmt.setString(paramIdx++, serialNumber);
}
if (isCertificateDeviceIdentifierProvided) {
stmt.setString(paramIdx++, deviceIdentifier);
}
if (isCertificateUsernameProvided) {
stmt.setString(paramIdx++, "%" + username + "%");
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx++, request.getRowCount());
resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
certificateResponse = new CertificateResponse(); certificateResponse = new CertificateResponse();
byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
@ -98,11 +172,11 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl {
certificateResponse.setUsername(resultSet.getString("USERNAME")); certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse); certificates.add(certificateResponse);
resultCount++;
} }
paginationResult = new PaginationResult(); paginationResult = new PaginationResult();
paginationResult.setData(certificates); paginationResult.setData(certificates);
paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); paginationResult.setRecordsTotal(this.getCertificateCount(request));
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificates.";
log.error(errorMsg, e); log.error(errorMsg, e);

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -44,24 +45,57 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl {
private static final Log log = LogFactory.getLog(OracleCertificateDAOImpl.class); private static final Log log = LogFactory.getLog(OracleCertificateDAOImpl.class);
@Override @Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
CertificateResponse certificateResponse; CertificateResponse certificateResponse;
List<CertificateResponse> certificates = new ArrayList<>(); List<CertificateResponse> certificates = new ArrayList<>();
PaginationResult paginationResult; PaginationResult paginationResult;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
boolean isCertificateSerialNumberProvided = false;
boolean isCertificateDeviceIdentifierProvided = false;
boolean isCertificateUsernameProvided = false;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " String query = "SELECT * " +
+ "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; "FROM DM_DEVICE_CERTIFICATE " +
stmt = conn.prepareStatement(sql); "WHERE TENANT_ID = ? ";
stmt.setInt(1, tenantId); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setInt(2, rowNum); query += "AND SERIAL_NUMBER = ? ";
stmt.setInt(3, limit); isCertificateSerialNumberProvided = true;
resultSet = stmt.executeQuery(); }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
query += "AND DEVICE_IDENTIFIER = ? ";
isCertificateDeviceIdentifierProvided = true;
}
if (username != null && !username.isEmpty()) {
query += "AND USERNAME LIKE ? ";
isCertificateUsernameProvided = true;
}
int resultCount = 0; query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(query);
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
if (isCertificateSerialNumberProvided) {
stmt.setString(paramIdx++, serialNumber);
}
if (isCertificateDeviceIdentifierProvided) {
stmt.setString(paramIdx++, deviceIdentifier);
}
if (isCertificateUsernameProvided) {
stmt.setString(paramIdx++, "%" + username + "%");
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx++, request.getRowCount());
resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
certificateResponse = new CertificateResponse(); certificateResponse = new CertificateResponse();
byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
@ -72,11 +106,10 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl {
certificateResponse.setUsername(resultSet.getString("USERNAME")); certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse); certificates.add(certificateResponse);
resultCount++;
} }
paginationResult = new PaginationResult(); paginationResult = new PaginationResult();
paginationResult.setData(certificates); paginationResult.setData(certificates);
paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); paginationResult.setRecordsTotal(this.getCertificateCount(request));
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificates.";
log.error(errorMsg, e); log.error(errorMsg, e);
@ -91,25 +124,63 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl {
return CertificateManagementDAOFactory.getConnection(); return CertificateManagementDAOFactory.getConnection();
} }
private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int certificateCount = 0; int certificateCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?");
"SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) { if (serialNumber != null && !serialNumber.isEmpty()) {
queryBuilder.append(" AND SERIAL_NUMBER = ?");
}
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
queryBuilder.append(" AND DEVICE_IDENTIFIER = ?");
}
if (username != null && !username.isEmpty()) {
queryBuilder.append(" AND USERNAME LIKE ?");
}
String sql = queryBuilder.toString();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { int paramIdx = 2;
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setString(paramIdx++, serialNumber);
} }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
stmt.setString(paramIdx++, deviceIdentifier);
} }
if (username != null && !username.isEmpty()) {
stmt.setString(paramIdx, "%" + username + "%");
}
rs = stmt.executeQuery();
if (rs.next()) {
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT");
} }
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificate count.";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new CertificateManagementDAOException(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e);
} finally {
CertificateManagementDAOUtil.cleanupResources(stmt, rs);
} }
return certificateCount; return certificateCount;
} }
} }

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -44,24 +45,57 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl {
private static final Log log = LogFactory.getLog(PostgreSQLCertificateDAOImpl.class); private static final Log log = LogFactory.getLog(PostgreSQLCertificateDAOImpl.class);
@Override @Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
CertificateResponse certificateResponse; CertificateResponse certificateResponse;
List<CertificateResponse> certificates = new ArrayList<>(); List<CertificateResponse> certificates = new ArrayList<>();
PaginationResult paginationResult; PaginationResult paginationResult;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
boolean isCertificateSerialNumberProvided = false;
boolean isCertificateDeviceIdentifierProvided = false;
boolean isCertificateUsernameProvided = false;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " String query = "SELECT * " +
+ "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?"; "FROM DM_DEVICE_CERTIFICATE " +
stmt = conn.prepareStatement(sql); "WHERE TENANT_ID = ? ";
stmt.setInt(1, tenantId); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setInt(2, limit); query += "AND SERIAL_NUMBER = ? ";
stmt.setInt(3, rowNum); isCertificateSerialNumberProvided = true;
resultSet = stmt.executeQuery(); }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
query += "AND DEVICE_IDENTIFIER = ? ";
isCertificateDeviceIdentifierProvided = true;
}
if (username != null && !username.isEmpty()) {
query += "AND USERNAME LIKE ? ";
isCertificateUsernameProvided = true;
}
int resultCount = 0; query += "ORDER BY ID LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(query);
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
if (isCertificateSerialNumberProvided) {
stmt.setString(paramIdx++, serialNumber);
}
if (isCertificateDeviceIdentifierProvided) {
stmt.setString(paramIdx++, deviceIdentifier);
}
if (isCertificateUsernameProvided) {
stmt.setString(paramIdx++, "%" + username + "%");
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx++, request.getRowCount());
resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
certificateResponse = new CertificateResponse(); certificateResponse = new CertificateResponse();
byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
@ -72,11 +106,11 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl {
certificateResponse.setUsername(resultSet.getString("USERNAME")); certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse); certificates.add(certificateResponse);
resultCount++;
} }
paginationResult = new PaginationResult(); paginationResult = new PaginationResult();
paginationResult.setData(certificates); paginationResult.setData(certificates);
paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); paginationResult.setRecordsTotal(this.getCertificateCount(request));
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificates.";
log.error(errorMsg, e); log.error(errorMsg, e);
@ -91,25 +125,63 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl {
return CertificateManagementDAOFactory.getConnection(); return CertificateManagementDAOFactory.getConnection();
} }
private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int certificateCount = 0; int certificateCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?");
"SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) { if (serialNumber != null && !serialNumber.isEmpty()) {
queryBuilder.append(" AND SERIAL_NUMBER = ?");
}
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
queryBuilder.append(" AND DEVICE_IDENTIFIER = ?");
}
if (username != null && !username.isEmpty()) {
queryBuilder.append(" AND USERNAME ILIKE ?");
}
String sql = queryBuilder.toString();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { int paramIdx = 2;
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setString(paramIdx++, serialNumber);
} }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
stmt.setString(paramIdx++, deviceIdentifier);
} }
if (username != null && !username.isEmpty()) {
stmt.setString(paramIdx, "%" + username + "%");
}
rs = stmt.executeQuery();
if (rs.next()) {
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT");
} }
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificate count.";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new CertificateManagementDAOException(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e);
} finally {
CertificateManagementDAOUtil.cleanupResources(stmt, rs);
} }
return certificateCount; return certificateCount;
} }
} }

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -44,24 +45,57 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl {
private static final Log log = LogFactory.getLog(SQLServerCertificateDAOImpl.class); private static final Log log = LogFactory.getLog(SQLServerCertificateDAOImpl.class);
@Override @Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
CertificateResponse certificateResponse; CertificateResponse certificateResponse;
List<CertificateResponse> certificates = new ArrayList<>(); List<CertificateResponse> certificates = new ArrayList<>();
PaginationResult paginationResult; PaginationResult paginationResult;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
boolean isCertificateSerialNumberProvided = false;
boolean isCertificateDeviceIdentifierProvided = false;
boolean isCertificateUsernameProvided = false;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " String query = "SELECT * " +
+ "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; "FROM DM_DEVICE_CERTIFICATE " +
stmt = conn.prepareStatement(sql); "WHERE TENANT_ID = ? ";
stmt.setInt(1, tenantId); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setInt(2, rowNum); query += "AND SERIAL_NUMBER = ? ";
stmt.setInt(3, limit); isCertificateSerialNumberProvided = true;
resultSet = stmt.executeQuery(); }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
query += "AND DEVICE_IDENTIFIER = ? ";
isCertificateDeviceIdentifierProvided = true;
}
if (username != null && !username.isEmpty()) {
query += "AND USERNAME LIKE ? ";
isCertificateUsernameProvided = true;
}
int resultCount = 0; query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(query);
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
if (isCertificateSerialNumberProvided) {
stmt.setString(paramIdx++, serialNumber);
}
if (isCertificateDeviceIdentifierProvided) {
stmt.setString(paramIdx++, deviceIdentifier);
}
if (isCertificateUsernameProvided) {
stmt.setString(paramIdx++, "%" + username + "%");
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx++, request.getRowCount());
resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
certificateResponse = new CertificateResponse(); certificateResponse = new CertificateResponse();
byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
@ -72,11 +106,11 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl {
certificateResponse.setUsername(resultSet.getString("USERNAME")); certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse); certificates.add(certificateResponse);
resultCount++;
} }
paginationResult = new PaginationResult(); paginationResult = new PaginationResult();
paginationResult.setData(certificates); paginationResult.setData(certificates);
paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); paginationResult.setRecordsTotal(this.getCertificateCount(request));
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificates.";
log.error(errorMsg, e); log.error(errorMsg, e);
@ -91,25 +125,63 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl {
return CertificateManagementDAOFactory.getConnection(); return CertificateManagementDAOFactory.getConnection();
} }
private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException {
int certificateCount = 0; int certificateCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String serialNumber = request.getSerialNumber();
String deviceIdentifier = request.getDeviceIdentifier();
String username = request.getUsername();
PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String sql = StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?");
"SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) { if (serialNumber != null && !serialNumber.isEmpty()) {
queryBuilder.append(" AND SERIAL_NUMBER = ?");
}
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
queryBuilder.append(" AND DEVICE_IDENTIFIER = ?");
}
if (username != null && !username.isEmpty()) {
queryBuilder.append(" AND USERNAME LIKE ?");
}
String sql = queryBuilder.toString();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { int paramIdx = 2;
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); if (serialNumber != null && !serialNumber.isEmpty()) {
stmt.setString(paramIdx++, serialNumber);
} }
if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) {
stmt.setString(paramIdx++, deviceIdentifier);
} }
if (username != null && !username.isEmpty()) {
stmt.setString(paramIdx, "%" + username + "%");
}
rs = stmt.executeQuery();
if (rs.next()) {
certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT");
} }
} catch (SQLException e) { } catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates."; String errorMsg = "SQL error occurred while retrieving the certificate count.";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new CertificateManagementDAOException(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e);
} finally {
CertificateManagementDAOUtil.cleanupResources(stmt, rs);
} }
return certificateCount; return certificateCount;
} }
} }

@ -17,6 +17,7 @@
*/ */
package io.entgra.device.mgt.core.certificate.mgt.core.service; package io.entgra.device.mgt.core.certificate.mgt.core.service;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException;
@ -71,9 +72,11 @@ public interface CertificateManagementService {
CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException; CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException;
PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException; PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException;
boolean removeCertificate(String certificateId) throws CertificateManagementException; boolean removeCertificate(String serialNumber) throws CertificateManagementException;
boolean getValidateMetaValue() throws CertificateManagementException;
List<CertificateResponse> getCertificates() throws CertificateManagementException; List<CertificateResponse> getCertificates() throws CertificateManagementException;

@ -17,6 +17,14 @@
*/ */
package io.entgra.device.mgt.core.certificate.mgt.core.service; package io.entgra.device.mgt.core.certificate.mgt.core.service;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants;
import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagerUtil;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO;
import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException;
import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory;
@ -27,12 +35,14 @@ import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreExceptio
import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.KeyStoreReader; import io.entgra.device.mgt.core.certificate.mgt.core.impl.KeyStoreReader;
import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants;
import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagerUtil; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import java.io.InputStream; import java.io.InputStream;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.cert.Certificate; import java.security.cert.Certificate;
@ -154,11 +164,11 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe
} }
@Override @Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException { public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException {
try { try {
CertificateManagementDAOFactory.openConnection(); CertificateManagementDAOFactory.openConnection();
CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO();
return certificateDAO.getAllCertificates(rowNum, CertificateManagerUtil.validateCertificateListPageSize(limit)); return certificateDAO.getAllCertificates(request);
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while opening a connection to the underlying data source"; String msg = "Error occurred while opening a connection to the underlying data source";
log.error(msg, e); log.error(msg, e);
@ -172,28 +182,52 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe
CertificateManagementDAOFactory.closeConnection(); CertificateManagementDAOFactory.closeConnection();
} }
} }
@Override @Override
public boolean removeCertificate(String certificateId) throws CertificateManagementException { public boolean removeCertificate(String serialNumber) throws CertificateManagementException {
try { try {
CertificateManagementDAOFactory.beginTransaction(); CertificateManagementDAOFactory.beginTransaction();
CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO();
boolean status = certificateDAO.removeCertificate(certificateId); boolean status = certificateDAO.removeCertificate(serialNumber);
CertificateManagementDAOFactory.commitTransaction(); CertificateManagementDAOFactory.commitTransaction();
return status; return status;
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
String msg = "Error occurred while removing certificate carrying certificate id '" + certificateId + "'"; String msg = "Error occurred while removing certificate carrying serialNumber '" + serialNumber + "'";
log.error(msg, e); log.error(msg, e);
throw new CertificateManagementException(msg, e); throw new CertificateManagementException(msg, e);
} catch (CertificateManagementDAOException e) { } catch (CertificateManagementDAOException e) {
CertificateManagementDAOFactory.rollbackTransaction(); CertificateManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while removing the certificate carrying certificate id '" + certificateId + String msg = "Error occurred while removing the certificate carrying serialNumber '" + serialNumber +
"' from the certificate repository"; "' from the certificate repository";
log.error(msg, e); log.error(msg, e);
throw new CertificateManagementException(msg, e); throw new CertificateManagementException(msg, e);
} }
} }
@Override
public boolean getValidateMetaValue() throws CertificateManagementException {
Metadata metadata;
try {
metadata = CertificateManagerUtil.getMetadataManagementService().retrieveMetadata(CertificateManagementConstants.CERTIFICATE_DELETE);
if (metadata != null) {
String metaValue = metadata.getMetaValue();
if (metaValue != null && !metaValue.isEmpty()) {
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(metaValue).getAsJsonObject();
return jsonObject.get(CertificateManagementConstants.IS_CERTIFICATE_DELETE_ENABLE).getAsBoolean();
}
}
return false;
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting the metadata entry for metaKey: " + CertificateManagementConstants.CERTIFICATE_DELETE;
log.error(msg, e);
throw new CertificateManagementException(msg, e);
} catch (JsonParseException e) {
String msg = "Error occurred while parsing the JSON metadata value for metaKey: " + CertificateManagementConstants.CERTIFICATE_DELETE;
log.error(msg, e);
throw new CertificateManagementException(msg, e);
}
}
@Override @Override
public List<CertificateResponse> getCertificates() throws CertificateManagementException { public List<CertificateResponse> getCertificates() throws CertificateManagementException {
try { try {

@ -41,6 +41,12 @@ public final class CertificateManagementConstants {
public static final int RSA_KEY_LENGTH = 2048; public static final int RSA_KEY_LENGTH = 2048;
public static final String SIGNING_ALGORITHM = "SHA256withRSA"; public static final String SIGNING_ALGORITHM = "SHA256withRSA";
public static final int DEFAULT_PAGE_LIMIT = 50;
public static final String CERTIFICATE_DELETE = "CERTIFICATE_DELETE";
public static final String IS_CERTIFICATE_DELETE_ENABLE = "isCertificateDelete";
public static final class DataBaseTypes { public static final class DataBaseTypes {
private DataBaseTypes() { private DataBaseTypes() {
throw new AssertionError(); throw new AssertionError();

@ -19,6 +19,7 @@
package io.entgra.device.mgt.core.certificate.mgt.core.util; package io.entgra.device.mgt.core.certificate.mgt.core.util;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@ -28,6 +29,7 @@ import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSour
import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.JNDILookupDefinition;
import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil;
import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.sql.DataSource; import javax.sql.DataSource;
import javax.xml.XMLConstants; import javax.xml.XMLConstants;
@ -41,6 +43,7 @@ public class CertificateManagerUtil {
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
public static final String MONITORING_FREQUENCY = "notifierFrequency"; public static final String MONITORING_FREQUENCY = "notifierFrequency";
private static MetadataManagementService metadataManagementService;
private static final Log log = LogFactory.getLog(CertificateManagerUtil.class); private static final Log log = LogFactory.getLog(CertificateManagerUtil.class);
public static Document convertToDocument(File file) throws CertificateManagementException { public static Document convertToDocument(File file) throws CertificateManagementException {
@ -105,4 +108,26 @@ public class CertificateManagerUtil {
return limit; return limit;
} }
/**
* Initializing and accessing method for MetadataManagementService.
*
* @return MetadataManagementService instance
* @throws IllegalStateException if metadataManagementService cannot be initialized
*/
public static MetadataManagementService getMetadataManagementService() {
if (metadataManagementService == null) {
synchronized (CertificateManagerUtil.class) {
if (metadataManagementService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
metadataManagementService = (MetadataManagementService) ctx.getOSGiService(
MetadataManagementService.class, null);
if (metadataManagementService == null) {
throw new IllegalStateException("Metadata Management service not initialized.");
}
}
}
}
return metadataManagementService;
}
} }

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.certificate.mgt.core.impl; package io.entgra.device.mgt.core.certificate.mgt.core.impl;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
@ -110,7 +111,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest
public void negativeTestGetAllCertificates() throws Exception { public void negativeTestGetAllCertificates() throws Exception {
PowerMockito.mockStatic(CertificateManagementDAOFactory.class); PowerMockito.mockStatic(CertificateManagementDAOFactory.class);
PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection");
instance.getAllCertificates(1, 2); CertificatePaginationRequest request = new CertificatePaginationRequest(0, 2);
instance.getAllCertificates(request);
} }
@Test(description = "This test case tests behaviour when an error occurs getting the list of certificates from repository" @Test(description = "This test case tests behaviour when an error occurs getting the list of certificates from repository"
@ -118,7 +120,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest
public void negativeTestGetAllCertificates2() throws Exception { public void negativeTestGetAllCertificates2() throws Exception {
CertificateManagementDAOFactory.init(daoExceptionDatasource); CertificateManagementDAOFactory.init(daoExceptionDatasource);
CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance();
instance1.getAllCertificates(1, 2); CertificatePaginationRequest request = new CertificatePaginationRequest(0, 2);
instance.getAllCertificates(request);
} }
@Test(description = "This test case tests behaviour when data source transaction error occurs when removing the certificate" @Test(description = "This test case tests behaviour when data source transaction error occurs when removing the certificate"

@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl;
import io.entgra.device.mgt.core.certificate.mgt.core.util.CSRGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.util.CSRGenerator;
import io.entgra.device.mgt.core.certificate.mgt.core.util.DummyCertificate; import io.entgra.device.mgt.core.certificate.mgt.core.util.DummyCertificate;
import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -217,7 +218,8 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC
public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException { public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException {
managementService.generateX509Certificate(); managementService.generateX509Certificate();
managementService.generateX509Certificate(); managementService.generateX509Certificate();
PaginationResult allCertificates = managementService.getAllCertificates(0, 2); CertificatePaginationRequest request = new CertificatePaginationRequest(0,2);
PaginationResult allCertificates = managementService.getAllCertificates(request);
Assert.assertEquals(allCertificates.getData().size(), 2); Assert.assertEquals(allCertificates.getData().size(), 2);
log.info("GetAllCertificatesPaginated Test Successful"); log.info("GetAllCertificatesPaginated Test Successful");
} }

@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
DEVICE_IDENTIFIER VARCHAR(300),
USERNAME VARCHAR(500) DEFAULT NULL, USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );

@ -0,0 +1,77 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.common;
public class CertificatePaginationRequest {
private int startIndex;
private int rowCount;
private String serialNumber;
private String deviceIdentifier;
private String username;
public CertificatePaginationRequest(int start, int rowCount) {
this.startIndex = start;
this.rowCount = rowCount;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "Certificate serial number '" + this.serialNumber + "' num of rows: " + this.rowCount + " start index: " + this.startIndex;
}
}
Loading…
Cancel
Save