Search in sources :

Example 16 with CertificateMetadataDTO

use of org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO in project carbon-apimgt by wso2.

the class CertificateMgtDAO method getClientCertificates.

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or api identifier.
 * Both alias and api identifier are optional
 *
 * @param tenantId      : The id of the tenant which the certificate belongs to.
 * @param alias         : Alias for the certificate. (Optional)
 * @param apiIdentifier : The API which the certificate is mapped to. (Optional)
 * @param organization  : Organization
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 */
public List<ClientCertificateDTO> getClientCertificates(int tenantId, String alias, APIIdentifier apiIdentifier, String organization) throws CertificateManagementException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    List<ClientCertificateDTO> clientCertificateDTOS = new ArrayList<>();
    int apiId = 0;
    int index = 1;
    String selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT;
    if (StringUtils.isNotEmpty(alias) && apiIdentifier != null) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_ALIAS_APIID;
    } else if (StringUtils.isNotEmpty(alias)) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_ALIAS;
    } else if (apiIdentifier != null) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_APIID;
    }
    try {
        connection = APIMgtDBUtil.getConnection();
        if (apiIdentifier != null) {
            String apiUuid;
            if (apiIdentifier.getUUID() != null) {
                apiUuid = apiIdentifier.getUUID();
                APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiUuid);
                if (apiRevision != null && apiRevision.getApiUUID() != null) {
                    apiUuid = apiRevision.getApiUUID();
                }
            } else {
                apiUuid = ApiMgtDAO.getInstance().getUUIDFromIdentifier(apiIdentifier, organization);
            }
            apiId = ApiMgtDAO.getInstance().getAPIID(apiUuid, connection);
        }
        preparedStatement = connection.prepareStatement(selectQuery);
        preparedStatement.setBoolean(index, false);
        index++;
        preparedStatement.setInt(index, tenantId);
        index++;
        if (alias != null) {
            preparedStatement.setString(index, alias);
            index++;
        }
        if (apiIdentifier != null) {
            preparedStatement.setInt(index, apiId);
        }
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            alias = resultSet.getString("ALIAS");
            ClientCertificateDTO clientCertificateDTO = new ClientCertificateDTO();
            clientCertificateDTO.setTierName(resultSet.getString("TIER_NAME"));
            clientCertificateDTO.setAlias(alias);
            clientCertificateDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(resultSet.getBinaryStream("CERTIFICATE")));
            if (apiIdentifier == null) {
                apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
            }
            clientCertificateDTO.setApiIdentifier(apiIdentifier);
            clientCertificateDTOS.add(clientCertificateDTO);
        }
    } catch (SQLException e) {
        handleException("Error while searching client certificate details for the tenant " + tenantId, e);
    } catch (APIManagementException e) {
        handleException("API Management Exception while searching client certificate details for the tenant " + tenantId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return clientCertificateDTOS;
}
Also used : APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 17 with CertificateMetadataDTO

use of org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO in project carbon-apimgt by wso2.

the class CertificateRestApiUtils method getPaginatedCertificates.

/**
 * Get the paginated list of certificates based on the limit and offset values provided.
 *
 * @param certificateMetadataList : The list of certificate metadata.
 * @param limit                   : The number of items per page.
 * @param offset                  : Page number
 * @param query                   : The query parameters.
 * @return : CertificatesDTO Object with the parameters set.
 */
public static CertificatesDTO getPaginatedCertificates(List<CertificateMetadataDTO> certificateMetadataList, int limit, int offset, String query) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Filter the certificates based on the pagination parameters, limit = %d and " + "offset = %d", limit, offset));
    }
    int certCount = certificateMetadataList.size();
    List<CertMetadataDTO> certificateList = new ArrayList<>();
    CertificatesDTO certificatesDTO = new CertificatesDTO();
    certificatesDTO.setCount(certCount > limit ? limit : certCount);
    // If the provided offset value exceeds the offset, reset the offset to default.
    if (offset > certCount) {
        offset = RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    }
    // Select only the set of Certificates which matches the given limit and offset values.
    int start = offset;
    int end = certCount > start + limit ? start + limit : certCount;
    for (int i = start; i < end; i++) {
        CertMetadataDTO certMetadataDTO = new CertMetadataDTO();
        CertificateMetadataDTO certificateMetadataDTO = certificateMetadataList.get(i);
        certMetadataDTO.setAlias(certificateMetadataDTO.getAlias());
        certMetadataDTO.setEndpoint(certificateMetadataDTO.getEndpoint());
        certificateList.add(certMetadataDTO);
    }
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, certCount);
    String paginatedPrevious = "";
    String paginatedNext = "";
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = getCertificatesPaginatedURL(RestApiConstants.CERTS_GET_PAGINATED_URL, paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = getCertificatesPaginatedURL(RestApiConstants.CERTS_GET_PAGINATED_URL, paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
    }
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setNext(paginatedNext);
    paginationDTO.setPrevious(paginatedPrevious);
    paginationDTO.setLimit(limit);
    paginationDTO.setOffset(offset);
    paginationDTO.setTotal(certCount);
    certificatesDTO.setCount(certificateList.size());
    certificatesDTO.setCertificates(certificateList);
    certificatesDTO.setPagination(paginationDTO);
    return certificatesDTO;
}
Also used : CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) ArrayList(java.util.ArrayList) PaginationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) CertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertMetadataDTO) ClientCertificatesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertificatesDTO) CertificatesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertificatesDTO)

Example 18 with CertificateMetadataDTO

use of org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO in project carbon-apimgt by wso2.

the class ExportUtils method getEndpointCertificateContentAndMetaData.

/**
 * Get Endpoint Certificate MetaData and Certificate detail and build JSON Array.
 *
 * @param tenantId          Tenant id of the user
 * @param url               Url of the endpoint
 * @param certDirectoryPath Directory path to export the certificates
 * @return JSON Array of certificate details
 * @throws APIImportExportException If an error occurs while retrieving endpoint certificate metadata and content
 */
private static JsonArray getEndpointCertificateContentAndMetaData(int tenantId, String url, String certDirectoryPath) throws APIImportExportException {
    List<CertificateMetadataDTO> certificateMetadataDTOS;
    CertificateManager certificateManager = CertificateManagerImpl.getInstance();
    try {
        certificateMetadataDTOS = certificateManager.getCertificates(tenantId, null, url);
    } catch (APIManagementException e) {
        throw new APIImportExportException("Error retrieving certificate meta data. For tenantId: " + tenantId + " hostname: " + url, e);
    }
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonArray certificatesList = new JsonArray();
    certificateMetadataDTOS.forEach(metadataDTO -> {
        try (ByteArrayInputStream certificate = certificateManager.getCertificateContent(metadataDTO.getAlias())) {
            byte[] certificateContent = IOUtils.toByteArray(certificate);
            String certificateContentEncoded = APIConstants.BEGIN_CERTIFICATE_STRING.concat(System.lineSeparator()).concat(new String(Base64.encodeBase64(certificateContent))).concat(System.lineSeparator()).concat(APIConstants.END_CERTIFICATE_STRING);
            CommonUtil.writeFile(certDirectoryPath + File.separator + metadataDTO.getAlias() + ".crt", certificateContentEncoded);
            // Add the file name to the Certificate Metadata
            JsonObject modifiedCertificateMetadata = (JsonObject) gson.toJsonTree(metadataDTO);
            modifiedCertificateMetadata.addProperty(ImportExportConstants.CERTIFICATE_FILE, metadataDTO.getAlias() + ".crt");
            certificatesList.add(modifiedCertificateMetadata);
        } catch (APIManagementException e) {
            log.error("Error retrieving certificate content. For tenantId: " + tenantId + " hostname: " + url + " alias: " + metadataDTO.getAlias(), e);
        } catch (IOException e) {
            log.error("Error while converting certificate content to Byte Array. For tenantId: " + tenantId + " hostname: " + url + " alias: " + metadataDTO.getAlias(), e);
        } catch (APIImportExportException e) {
            log.error("Error while writing the certificate content. For tenantId: " + tenantId + " hostname: " + url + " alias: " + metadataDTO.getAlias(), e);
        }
    });
    return certificatesList;
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) CertificateManager(org.wso2.carbon.apimgt.impl.certificatemgt.CertificateManager) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) ByteArrayInputStream(java.io.ByteArrayInputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)

Aggregations

CertificateMetadataDTO (org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO)17 ArrayList (java.util.ArrayList)9 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 IOException (java.io.IOException)4 CertificateManagementException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException)4 Gson (com.google.gson.Gson)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 SQLException (java.sql.SQLException)3 CertificateAliasExistsException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException)3 JsonArray (com.google.gson.JsonArray)2 JsonObject (com.google.gson.JsonObject)2 InputStream (java.io.InputStream)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)2 CertMetadataDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertMetadataDTO)2