From 017c70fa084676003dd086ea2f7c75430528b3eb Mon Sep 17 00:00:00 2001 From: nishan Date: Fri, 14 Jul 2023 00:08:27 +0530 Subject: [PATCH 1/2] Fix Certificate test case and delete and search option --- .../CertificateManagementAdminService.java | 41 ++++-- ...CertificateManagementAdminServiceImpl.java | 64 ++++++--- .../admin/api/util/RequestValidationUtil.java | 8 -- .../pom.xml | 7 +- .../mgt/core/dao/CertificateDAO.java | 11 +- .../dao/impl/AbstractCertificateDAOImpl.java | 12 +- .../dao/impl/GenericCertificateDAOImpl.java | 122 ++++++++++++++---- .../dao/impl/OracleCertificateDAOImpl.java | 117 +++++++++++++---- .../impl/PostgreSQLCertificateDAOImpl.java | 118 +++++++++++++---- .../dao/impl/SQLServerCertificateDAOImpl.java | 118 +++++++++++++---- .../service/CertificateManagementService.java | 7 +- .../CertificateManagementServiceImpl.java | 54 ++++++-- .../util/CertificateManagementConstants.java | 6 + .../mgt/core/util/CertificateManagerUtil.java | 25 ++++ ...ateManagementServiceImplNegativeTests.java | 7 +- ...CertificateManagementServiceImplTests.java | 4 +- .../src/test/resources/sql/h2.sql | 1 + .../common/CertificatePaginationRequest.java | 77 +++++++++++ 18 files changed, 643 insertions(+), 156 deletions(-) create mode 100644 components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java index 18207be106b..cd2be07ac99 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java @@ -247,14 +247,15 @@ public interface CertificateManagementAdminService { * * @return paginated result of certificate. */ + @GET @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "Getting Details of Certificates", - notes = "Get all the details of the certificates you have used for mutual SSL. In a situation where you wish to " - + "view all the certificate details, it is not feasible to show all the details on one " + value = "Getting Details of search Certificates", + 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 search certificate details, it is not feasible to show all the details on one " + "page. Therefore, the details are paginated.", tags = "Certificate Management", extensions = { @@ -308,24 +309,42 @@ public interface CertificateManagementAdminService { }) Response getAllCertificates( @ApiParam( - name = "offset", - value = "The starting pagination index for the complete list of qualified items.", + name = "serialNumber", + value = "The serial number of the certificates", required = false, defaultValue = "0") - @QueryParam("offset") int offset, + @QueryParam("serialNumber") String serialNumber, @ApiParam( - name = "limit", - value = "Provide how many certificate details you require from the starting pagination index/offset.", + name = "deviceIdentifier", + value = "The device identifier of the certificates", required = false, - defaultValue = "5") - @QueryParam("limit") int limit, + defaultValue = "0") + @QueryParam("deviceIdentifier") String deviceIdentifier, + @ApiParam( + name = "username", + value = "User name of the certificate added user" , + required = false, + defaultValue = "0") + @QueryParam("username") String username, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @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 @ApiOperation( diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index c64df487be9..3f124a89465 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -18,7 +18,6 @@ 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.GET; import javax.ws.rs.HeaderParam; @@ -26,7 +25,8 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; 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.LogFactory; 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.setSerial(enrollmentCertificate.getSerial()); 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); } certificateService.saveCertificate(certificates); @@ -131,13 +138,24 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem */ @GET public Response getAllCertificates( - @QueryParam("offset") int offset, - @QueryParam("limit") int limit, - @HeaderParam("If-Modified-Since") String ifModifiedSince) { + @QueryParam("serialNumber") String serialNumber, @QueryParam("deviceIdentifier") String deviceIdentifier, + @QueryParam("username") String username, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, + @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationInfo(offset, limit); 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 { - PaginationResult result = certificateService.getAllCertificates(offset, limit); + PaginationResult result = certificateService.getAllCertificates(request); CertificateList certificates = new CertificateList(); certificates.setCount(result.getRecordsTotal()); certificates.setList((List) result.getData()); @@ -151,20 +169,34 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem } @DELETE - public Response removeCertificate(@QueryParam("certificateId") String certificateId) { - RequestValidationUtil.validateCertificateId(certificateId); + public Response removeCertificate(@QueryParam("serialNumber") String serialNumber) { + RequestValidationUtil.validateSerialNumber(serialNumber); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { - boolean status = certificateService.removeCertificate(certificateId); - if (!status) { - return Response.status(Response.Status.NOT_FOUND).entity( - "No certificate is found with the given " + - "certificate id '" + certificateId + "'").build(); + boolean decision = certificateService.getValidateMetaValue(); + if (decision) { + try { + boolean status = certificateService.removeCertificate(serialNumber); + if (!status) { + return Response.status(Response.Status.NOT_FOUND).entity( + "No certificate is found with the given " + + "serial number '" + serialNumber + "'").build(); + } else { + return Response.status(Response.Status.OK).entity( + "Certificate that carries the serial number '" + + serialNumber + "' has been removed").build(); + } + } catch (CertificateManagementException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } } else { - return Response.status(Response.Status.OK).entity( - "Certificate that carries the certificate id '" + - certificateId + "' has been removed").build(); + return Response.status(Response.Status.NOT_FOUND).entity( + "User not have to access delete certificate " + + "serial number '" + serialNumber + "'").build(); } } catch (CertificateManagementException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java index 6263ac9e462..43f4d1ab48e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java @@ -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) { if (offset < 0) { throw new InputValidationException( diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml index 84d4790af8b..cb44ff8045f 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml @@ -95,7 +95,8 @@ io.entgra.device.mgt.core.device.mgt.core.*, org.wso2.carbon.registry.indexing.*, javax.cache.*, - javax.naming.ldap + javax.naming.ldap, + com.google.gson.* @@ -253,6 +254,10 @@ slf4j-simple test + + com.googlecode.json-simple.wso2 + json-simple + diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java index a3200621d16..068766f3b93 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java @@ -18,8 +18,10 @@ 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.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 java.util.List; @@ -75,13 +77,12 @@ public interface CertificateDAO { /** * Get all the certificates in a paginated manner. * - * @param rowNum Stating index of the paginated result. - * @param limit Number of records to return. + * @param request index of the paginated result. * @return Pagination result with data and the count of results. * @throws CertificateManagementDAOException * */ - PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException; + PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException; /** * Get all the certificates. @@ -95,10 +96,10 @@ public interface CertificateDAO { /** * Delete a certificate identified by a serial number() * - * @param certificateId number + * @param serialNumber number * @return whether the certificate was removed or not. */ - boolean removeCertificate(String certificateId) throws CertificateManagementDAOException; + boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; List searchCertificate(String serialNumber) throws CertificateManagementDAOException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index 8e87ffff380..78ea14c99f3 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -237,7 +237,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { 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"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -247,8 +247,6 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -265,7 +263,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ } @Override - public boolean removeCertificate(String certificateId) throws CertificateManagementDAOException { + public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -273,15 +271,15 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ try { conn = this.getConnection(); String query = - "DELETE FROM DM_DEVICE_CERTIFICATE WHERE ID = ?" + + "DELETE FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" + " AND TENANT_ID = ? "; stmt = conn.prepareStatement(query); - stmt.setString(1, certificateId); + stmt.setString(1, serialNumber); stmt.setInt(2, tenantId); return stmt.executeUpdate() > 0; } 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); throw new CertificateManagementDAOException(msg, e); } finally { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index f3cba82857f..b24cc7625ed 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -18,6 +18,7 @@ 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.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -47,47 +48,120 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { 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 { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + 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); + + int paramIdx = 2; + 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) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + + @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; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); 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 { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, 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, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + 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()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -98,11 +172,11 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -112,4 +186,4 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { } return paginationResult; } -} +} \ No newline at end of file diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index f326f9cf97f..7941cb60b72 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -18,6 +18,7 @@ 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.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -44,24 +45,57 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(OracleCertificateDAOImpl.class); @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; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); 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 { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + 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()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -72,11 +106,10 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -91,25 +124,63 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { 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 { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + 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); + + int paramIdx = 2; + 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) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 7d187cfa3d6..1c84fccbe07 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -18,6 +18,7 @@ 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.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -44,24 +45,57 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(PostgreSQLCertificateDAOImpl.class); @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; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); 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 { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, limit); - stmt.setInt(3, rowNum); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + 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()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -72,11 +106,11 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -91,25 +125,63 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { 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 { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + 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); + + int paramIdx = 2; + 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) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 6615ab4c125..9fe8733264e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -18,6 +18,7 @@ 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.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -44,24 +45,57 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(SQLServerCertificateDAOImpl.class); @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; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); 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 { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + 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()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -72,11 +106,11 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -91,25 +125,63 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { 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 { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + 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); + + int paramIdx = 2; + 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) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java index 61d333413e5..611295ba3fe 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java @@ -17,6 +17,7 @@ */ 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.SCEPResponse; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; @@ -71,9 +72,11 @@ public interface CertificateManagementService { 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 getCertificates() throws CertificateManagementException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java index bcd696f21e4..047c5321971 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -17,6 +17,14 @@ */ 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.CertificateManagementDAOException; 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.impl.CertificateGenerator; 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.LogFactory; import org.bouncycastle.pkcs.PKCS10CertificationRequest; + import java.io.InputStream; import java.security.PrivateKey; import java.security.cert.Certificate; @@ -154,46 +164,70 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - return certificateDAO.getAllCertificates(rowNum, CertificateManagerUtil.validateCertificateListPageSize(limit)); + return certificateDAO.getAllCertificates(request); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { String msg = "Error occurred while looking up for the list of certificates managed in the underlying " + - "certificate repository"; + "certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } - @Override - public boolean removeCertificate(String certificateId) throws CertificateManagementException { + public boolean removeCertificate(String serialNumber) throws CertificateManagementException { try { CertificateManagementDAOFactory.beginTransaction(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - boolean status = certificateDAO.removeCertificate(certificateId); + boolean status = certificateDAO.removeCertificate(serialNumber); CertificateManagementDAOFactory.commitTransaction(); return status; } 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); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { 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"; log.error(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 public List getCertificates() throws CertificateManagementException { try { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java index 8235b3ee775..f851bd05f09 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java @@ -41,6 +41,12 @@ public final class CertificateManagementConstants { public static final int RSA_KEY_LENGTH = 2048; 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 { private DataBaseTypes() { throw new AssertionError(); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java index cfa613ba5a5..2da3d4d4146 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java @@ -19,6 +19,7 @@ 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.LogFactory; 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.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.sql.DataSource; import javax.xml.XMLConstants; @@ -41,6 +43,7 @@ public class CertificateManagerUtil { public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String MONITORING_FREQUENCY = "notifierFrequency"; + private static MetadataManagementService metadataManagementService; private static final Log log = LogFactory.getLog(CertificateManagerUtil.class); public static Document convertToDocument(File file) throws CertificateManagementException { @@ -105,4 +108,26 @@ public class CertificateManagerUtil { 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; + } + } \ No newline at end of file diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java index b1ce7cb8b6a..7aff1cd5866 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java @@ -18,6 +18,7 @@ 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.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; @@ -110,7 +111,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest public void negativeTestGetAllCertificates() throws Exception { PowerMockito.mockStatic(CertificateManagementDAOFactory.class); 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" @@ -118,7 +120,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest public void negativeTestGetAllCertificates2() throws Exception { CertificateManagementDAOFactory.init(daoExceptionDatasource); 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" diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java index ff6ad09e889..a57bfbb4d0e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java @@ -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.DummyCertificate; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -217,7 +218,8 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException { 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); log.info("GetAllCertificatesPaginated Test Successful"); } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql index 46582aa390d..0fb769e4062 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql @@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, + DEVICE_IDENTIFIER VARCHAR(300), USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) ); \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java new file mode 100644 index 00000000000..fdfcf5d30c4 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java @@ -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; + } +} From dbc73d18ede97983f30b5e7480332f9e62902a9b Mon Sep 17 00:00:00 2001 From: navodzoysa Date: Thu, 24 Aug 2023 16:05:14 +0530 Subject: [PATCH 2/2] Add improvements to certificate component --- .../CertificateManagementAdminService.java | 11 +- ...CertificateManagementAdminServiceImpl.java | 23 +-- .../pom.xml | 1 + .../dao/impl/GenericCertificateDAOImpl.java | 136 +++++++++--------- .../dao/impl/OracleCertificateDAOImpl.java | 126 ++++++++-------- .../impl/PostgreSQLCertificateDAOImpl.java | 127 ++++++++-------- .../dao/impl/SQLServerCertificateDAOImpl.java | 127 ++++++++-------- .../CertificateManagementServiceImpl.java | 5 +- 8 files changed, 265 insertions(+), 291 deletions(-) diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java index cd2be07ac99..af77d747192 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java @@ -311,20 +311,17 @@ public interface CertificateManagementAdminService { @ApiParam( name = "serialNumber", value = "The serial number of the certificates", - required = false, - defaultValue = "0") + required = false) @QueryParam("serialNumber") String serialNumber, @ApiParam( name = "deviceIdentifier", value = "The device identifier of the certificates", - required = false, - defaultValue = "0") + required = false) @QueryParam("deviceIdentifier") String deviceIdentifier, @ApiParam( name = "username", - value = "User name of the certificate added user" , - required = false, - defaultValue = "0") + value = "User name of the certificate added user", + required = false) @QueryParam("username") String username, @ApiParam( name = "If-Modified-Since", diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index 3f124a89465..815e141f38e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -27,6 +27,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.CertificateManagementAdminService; @@ -138,20 +139,23 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem */ @GET public Response getAllCertificates( - @QueryParam("serialNumber") String serialNumber, @QueryParam("deviceIdentifier") String deviceIdentifier, - @QueryParam("username") String username, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, + @QueryParam("serialNumber") String serialNumber, + @QueryParam("deviceIdentifier") String deviceIdentifier, + @QueryParam("username") String username, + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @QueryParam("offset") int offset, @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationInfo(offset, limit); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); CertificatePaginationRequest request = new CertificatePaginationRequest(offset, limit); - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { request.setSerialNumber(serialNumber); } - if (deviceIdentifier != null){ + if (StringUtils.isNotEmpty(deviceIdentifier)){ request.setDeviceIdentifier(deviceIdentifier); } - if (username != null){ + if (StringUtils.isNotEmpty(username)){ request.setUsername(username); } try { @@ -188,18 +192,19 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem serialNumber + "' has been removed").build(); } } catch (CertificateManagementException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; + String msg = "Error occurred while removing certificate with the given " + + "serial number '" + serialNumber + "'"; 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 " + + return Response.status(Response.Status.UNAUTHORIZED).entity( + "User unauthorized to delete certificate with " + "serial number '" + serialNumber + "'").build(); } } catch (CertificateManagementException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; + String msg = "Error occurred while getting the metadata entry for certificate deletion."; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml index cb44ff8045f..ef8abbba072 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml @@ -56,6 +56,7 @@ org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.apache.commons.lang, org.apache.commons.logging, org.apache.commons.collections.map, javax.security.auth.x500, diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index b24cc7625ed..7655e46005b 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -21,11 +21,11 @@ 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.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -55,66 +55,58 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME LIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; } - String sql = queryBuilder.toString(); - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - - int paramIdx = 2; - 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"); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } - @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -130,59 +122,59 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } query += "ORDER BY ID LIMIT ?,?"; - stmt = conn.prepareStatement(query); - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + try (PreparedStatement 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()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - 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()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); - } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index 7941cb60b72..9231a0d746a 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -21,11 +21,11 @@ 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.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -47,8 +47,6 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -64,58 +62,58 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } 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); + try (PreparedStatement 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()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - 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()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -130,56 +128,52 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME LIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; } - String sql = queryBuilder.toString(); - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 1c84fccbe07..e31e005f0bb 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -21,11 +21,11 @@ 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.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -47,8 +47,6 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -64,59 +62,58 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } query += "ORDER BY ID LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(query); - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + try (PreparedStatement 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()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - 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()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); - } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -131,56 +128,52 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME ILIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME ILIKE ?"; } - String sql = queryBuilder.toString(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } - - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 9fe8733264e..6e0908a286e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -21,11 +21,11 @@ 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.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -47,8 +47,6 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -64,59 +62,58 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } 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); + try (PreparedStatement 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()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - 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()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); - } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -131,56 +128,52 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME LIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; } - String sql = queryBuilder.toString(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } - - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 047c5321971..06cbedfb4d7 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -17,8 +17,6 @@ */ 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; @@ -38,6 +36,7 @@ import io.entgra.device.mgt.core.certificate.mgt.core.impl.KeyStoreReader; 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.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.pkcs.PKCS10CertificationRequest; @@ -210,7 +209,7 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe metadata = CertificateManagerUtil.getMetadataManagementService().retrieveMetadata(CertificateManagementConstants.CERTIFICATE_DELETE); if (metadata != null) { String metaValue = metadata.getMetaValue(); - if (metaValue != null && !metaValue.isEmpty()) { + if (StringUtils.isNotEmpty(metaValue)) { JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(metaValue).getAsJsonObject(); return jsonObject.get(CertificateManagementConstants.IS_CERTIFICATE_DELETE_ENABLE).getAsBoolean();