diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
index 6c586c3089..8a1dcef4da 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
@@ -162,6 +162,21 @@
org.testng
testng
+
+ com.h2database.wso2
+ h2-database-engine
+ test
+
+
+ org.powermock
+ powermock-api-mockito
+ test
+
+
+ org.powermock
+ powermock-module-testng
+ test
+
org.wso2.carbon
org.wso2.carbon.logging
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java
index 5c82ea83a3..10e70a5baa 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java
@@ -115,7 +115,7 @@ public class CertificateManagementDAOFactory {
currentTxState.set(TxState.CONNECTION_BORROWED);
}
- public static void openConnection() throws SQLException {
+ public static void openConnection() throws SQLException {
Connection conn = currentConnection.get();
if (conn != null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java
new file mode 100644
index 0000000000..38a16a7fa0
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.certificate.mgt.core.common;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.tomcat.jdbc.pool.PoolProperties;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeSuite;
+import org.w3c.dom.Document;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.wso2.carbon.certificate.mgt.core.util.TestUtils;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
+import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
+import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
+
+import javax.sql.DataSource;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import java.io.File;
+import java.sql.Connection;
+import java.sql.Statement;
+
+
+public abstract class BaseDeviceManagementCertificateTest {
+ private DataSource dataSource;
+ private static final Log log = LogFactory.getLog(BaseDeviceManagementCertificateTest.class);
+ private static final String DATASOURCE_LOCATION = "src/test/resources/data-source-config.xml";
+
+ @BeforeSuite
+ public void setupDataSource() throws Exception {
+ this.initDataSource();
+ this.initSQLScript();
+ initializeCarbonContext();
+ }
+
+ public void initDataSource() throws Exception {
+ this.dataSource = this.getDataSource(this.readDataSourceConfig());
+ DeviceManagementDAOFactory.init(dataSource);
+ GroupManagementDAOFactory.init(dataSource);
+ }
+
+ public void initDataSource(DataSource ds) throws Exception {
+ this.dataSource = ds;
+ DeviceManagementDAOFactory.init(dataSource);
+ GroupManagementDAOFactory.init(dataSource);
+ }
+
+ @BeforeClass
+ public abstract void init() throws Exception;
+
+ private DataSource getDataSource(DataSourceConfig config) {
+ PoolProperties properties = new PoolProperties();
+ properties.setUrl(config.getUrl());
+ properties.setDriverClassName(config.getDriverClassName());
+ properties.setUsername(config.getUser());
+ properties.setPassword(config.getPassword());
+ return new org.apache.tomcat.jdbc.pool.DataSource(properties);
+ }
+
+ private DataSourceConfig readDataSourceConfig() throws DeviceManagementException {
+ try {
+ File file = new File(DATASOURCE_LOCATION);
+ Document doc = DeviceManagerUtil.convertToDocument(file);
+ JAXBContext testDBContext = JAXBContext.newInstance(DataSourceConfig.class);
+ Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
+ return (DataSourceConfig) unmarshaller.unmarshal(doc);
+ } catch (JAXBException e) {
+ throw new DeviceManagementException("Error occurred while reading data source configuration", e);
+ }
+ }
+
+ private void initSQLScript() throws Exception {
+ Connection conn = null;
+ Statement stmt = null;
+ try {
+ conn = this.getDataSource().getConnection();
+ stmt = conn.createStatement();
+ stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/h2.sql'");
+ } finally {
+ TestUtils.cleanupResources(conn, stmt, null);
+ }
+ }
+
+ private void initializeCarbonContext() {
+
+ if (System.getProperty("carbon.home") == null) {
+ File file = new File("src/test/resources/carbon-home");
+ if (file.exists()) {
+ System.setProperty("carbon.home", file.getAbsolutePath());
+ }
+ file = new File("../resources/carbon-home");
+ if (file.exists()) {
+ System.setProperty("carbon.home", file.getAbsolutePath());
+ }
+ file = new File("../../resources/carbon-home");
+ if (file.exists()) {
+ System.setProperty("carbon.home", file.getAbsolutePath());
+ }
+ file = new File("../../../resources/carbon-home");
+ if (file.exists()) {
+ System.setProperty("carbon.home", file.getAbsolutePath());
+ }
+ }
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
+ .SUPER_TENANT_DOMAIN_NAME);
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
+ }
+
+ public DataSource getDataSource() {
+ return dataSource;
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/DataSourceConfig.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/DataSourceConfig.java
new file mode 100644
index 0000000000..f3154d3bdc
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/DataSourceConfig.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.common;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Model class for DataSourceConfig.
+ */
+@XmlRootElement(name = "DataSourceConfig")
+public class DataSourceConfig {
+
+ private String url;
+ private String driverClassName;
+ private String user;
+ private String password;
+
+ @Override
+ public String toString() {
+ return "DataSourceConfig[" +
+ " Url ='" + url + '\'' +
+ ", DriverClassName ='" + driverClassName + '\'' +
+ ", UserName ='" + user + '\'' +
+ ", Password ='" + password + '\'' +
+ "]";
+ }
+
+ @XmlElement(name = "Url", nillable = false)
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ @XmlElement(name = "DriverClassName", nillable = false)
+ public String getDriverClassName() {
+ return driverClassName;
+ }
+
+ public void setDriverClassName(String driverClassName) {
+ this.driverClassName = driverClassName;
+ }
+
+ @XmlElement(name = "User", nillable = false)
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ @XmlElement(name = "Password", nillable = false)
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java
new file mode 100644
index 0000000000..a7e0629e5d
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.certificate.mgt.core.impl;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.cert.jcajce.JcaCertStore;
+import org.bouncycastle.cms.CMSAbsentContent;
+import org.bouncycastle.cms.CMSException;
+import org.bouncycastle.cms.CMSSignedData;
+import org.bouncycastle.cms.CMSSignedDataGenerator;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.wso2.carbon.certificate.mgt.core.common.BaseDeviceManagementCertificateTest;
+import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
+import org.wso2.carbon.certificate.mgt.core.dto.CAStatus;
+import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
+import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
+import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl;
+import org.wso2.carbon.certificate.mgt.core.service.PaginationResult;
+import org.wso2.carbon.certificate.mgt.core.util.CSRGenerator;
+import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants;
+import org.wso2.carbon.certificate.mgt.core.util.DummyCertificate;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
+import sun.misc.BASE64Encoder;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.security.KeyPair;
+import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.*;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Test cases for for CertificateManagementServiceImpl class methods.
+ *
+ */
+public class CertificateManagementServiceImplTests extends BaseDeviceManagementCertificateTest {
+
+ private static Log log = LogFactory.getLog(CertificateManagementServiceImplTests.class);
+ private static final String CA_CERT_PEM = "src/test/resources/ca_cert.pem";
+ private static final String RA_CERT_PEM = "src/test/resources/ra_cert.pem";
+ private CertificateManagementServiceImpl managementService;
+
+ @BeforeClass
+ public void init() throws Exception {
+ initDataSource();
+ CertificateManagementDAOFactory.init(this.getDataSource());
+ //set Bouncycastle as a provider for testing
+ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+ //save certificatemanagementservice instance as class variable
+ managementService = CertificateManagementServiceImpl.getInstance();
+ Assert.assertNotNull(managementService);
+ log.info("getInstance Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of CA Certificate from the keystore")
+ public void testGetCACertificate() throws KeystoreException {
+ CertificateManagementServiceImpl instance = CertificateManagementServiceImpl.getInstance();
+ Certificate caCertificate = instance.getCACertificate();
+ Assert.assertNotNull(caCertificate);
+ Assert.assertEquals(caCertificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GetCACertificate Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of RA Certificate from the keystore")
+ public void testGetRACertificate() throws KeystoreException {
+ Certificate raCertificate = managementService.getRACertificate();
+ Assert.assertNotNull(raCertificate);
+ Assert.assertEquals(raCertificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GetRACertificate Test Successful");
+ }
+
+ @Test(description = "This test case test generation of root certificates")
+ public void testGetRootCertificate() throws IOException, KeystoreException {
+ File caCert = new File(CA_CERT_PEM);
+ File raCert = new File(RA_CERT_PEM);
+ //read file to byte arrays
+ byte[] caBytes = FileUtils.readFileToByteArray(caCert);
+ byte[] raBytes = FileUtils.readFileToByteArray(raCert);
+ List rootCertificates = managementService.getRootCertificates(caBytes, raBytes);
+ Assert.assertNotNull(rootCertificates);
+ Assert.assertEquals(rootCertificates.get(0).getType(), CertificateManagementConstants.X_509);
+ Assert.assertEquals(rootCertificates.get(1).getType(), CertificateManagementConstants.X_509);
+ log.info("GetRootCertificate Test Successful");
+ }
+
+ @Test(description = "This test case tests generation of X509Certificate")
+ public void testGenerateX509Certificate() throws KeystoreException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ Assert.assertNotNull(x509Certificate);
+ Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GenerateX509Certificate Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieving SCEP CA Certificate")
+ public void testGetCACertSCEP() throws KeystoreException {
+ SCEPResponse caCertSCEP = managementService.getCACertSCEP();
+ Assert.assertNotNull(caCertSCEP);
+ Assert.assertEquals(caCertSCEP.getResultCriteria(), CAStatus.CA_RA_CERT_RECEIVED);
+ log.info("GetCACertSCEP Test Successful");
+ }
+
+ @Test
+ public void testGetCACapsSCEP() {
+ byte[] caCapsSCEP = managementService.getCACapsSCEP();
+ Assert.assertNotNull(caCapsSCEP);
+ Assert.assertEquals(caCapsSCEP, CertificateManagementConstants.POST_BODY_CA_CAPS.getBytes());
+ log.info("GetCACapsSCEP Test Successful");
+ }
+
+ @Test(description = "This test case tests generation of a X509Certificate from a CSR")
+ public void testGenerateCertificateFromCSR() throws KeystoreException, IOException {
+ CSRGenerator csrGeneration = new CSRGenerator();
+ KeyStoreReader keyStoreReader = new KeyStoreReader();
+ // Generate key pair
+ KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
+ byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
+ PKCS10CertificationRequest certificationRequest;
+ PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
+ X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
+ certificationRequest = new PKCS10CertificationRequest(csrData);
+ X509Certificate x509Certificate = managementService.generateCertificateFromCSR(privateKeyCA,
+ certificationRequest, certCA.getIssuerX500Principal().getName());
+ Assert.assertNotNull(x509Certificate);
+ Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GenerateCertificateFromCSR Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of a Certificate from the keystore from the Serial Number")
+ public void testGetCertificateBySerial() throws KeystoreException, DeviceManagementException {
+ X509Certificate x509Certificate = null;
+ //generate and save a certificate
+ x509Certificate = managementService.generateX509Certificate();
+ //initialize DeviceConfigurationManager
+ DeviceConfigurationManager.getInstance().initConfig();
+ CertificateResponse certificateBySerial = managementService.getCertificateBySerial(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateBySerial);
+ Assert.assertEquals(certificateBySerial.getSerialNumber(), x509Certificate.getSerialNumber().toString());
+ log.info("GetCertificateBySerial Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of a Certificate from the keystore from the Alias")
+ public void testGetCertificateByAlias() throws KeystoreException, DeviceManagementException {
+ X509Certificate x509Certificate = null;
+ //generate and save a certificate
+ x509Certificate = managementService.generateX509Certificate();
+ //initialize DeviceConfigurationManager
+ DeviceConfigurationManager.getInstance().initConfig();
+ Certificate certificateByAlias = managementService.getCertificateByAlias(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateByAlias);
+ Assert.assertEquals(certificateByAlias.getType(), CertificateManagementConstants.X_509);
+ log.info("GetCertificateByAlias Test Successful");
+ }
+
+ @Test(description = "This test case tests Signature verification of a Certificate against the keystore")
+ public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
+ BASE64Encoder encoder = new BASE64Encoder();
+ //generate and save a certificate in the keystore
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ //Generate CMSdata
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ List list = new ArrayList<>();
+ list.add(x509Certificate);
+ JcaCertStore store = new JcaCertStore(list);
+ generator.addCertificates(store);
+ CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
+ byte[] signature = degenerateSd.getEncoded();
+ boolean verifySignature = managementService.verifySignature(encoder.encode(signature));
+ Assert.assertNotNull(verifySignature);
+ Assert.assertTrue(verifySignature);
+ log.info("VerifySignature Test Successful");
+ }
+
+ @Test(description = "This test case tests DN verification of a Certificate against the keystore")
+ public void testVerifySubjectDN() throws DeviceManagementException, KeystoreException {
+ DeviceConfigurationManager.getInstance().initConfig();
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ log.info(x509Certificate.getIssuerX500Principal().getName());
+ managementService.verifySubjectDN(x509Certificate.getIssuerDN().getName());
+ }
+
+ @Test(description = "This test case tests retrieval of a Certificate from the keystore from the Serial")
+ public void testRetrieveCertificate() throws KeystoreException, CertificateManagementException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ CertificateResponse certificateResponse = managementService.retrieveCertificate(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateResponse);
+ Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateserial());
+ }
+
+ @Test(description = "This test case tests the retrieval of Certificates from keystore in desired pagination")
+ public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException {
+ managementService.generateX509Certificate();
+ managementService.generateX509Certificate();
+ PaginationResult allCertificates = managementService.getAllCertificates(0, 2);
+ Assert.assertEquals(allCertificates.getData().size(), 2);
+ log.info("GetAllCertificatesPaginated Test Successful");
+ }
+
+ @Test(description = "This test casae tests retrieval of all Certificates from keystore")
+ public void testGetCertificates() throws CertificateManagementException, KeystoreException {
+ List certificatesBefore = managementService.getCertificates();
+ managementService.generateX509Certificate();
+ managementService.generateX509Certificate();
+ List certificatesAfter = managementService.getCertificates();
+ Assert.assertNotNull(certificatesBefore);
+ Assert.assertNotNull(certificatesAfter);
+ Assert.assertEquals((certificatesBefore.size() + 2), certificatesAfter.size());
+ log.info("GetCertificates Test Successful");
+ }
+
+ @Test(description = "This test case tests deleting Certificate from the keystore")
+ public void testRemoveCertificate() throws CertificateManagementException, KeystoreException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ List certificates = managementService.getCertificates();
+ int size = certificates.size();
+ boolean removed = managementService.removeCertificate(x509Certificate.getSerialNumber().toString());
+ certificates = managementService.getCertificates();
+ int sizeAfter = certificates.size();
+ Assert.assertNotNull(removed);
+ Assert.assertTrue(removed);
+ Assert.assertEquals((size - 1), sizeAfter);
+ log.info("RemoveCertificate Test Successful");
+ }
+
+
+ @Test(description = "This test case tests searching for a list of certificates by the serial number")
+ public void testSearchCertificates() throws CertificateManagementException, KeystoreException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ List certificateResponses = managementService.searchCertificates(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateResponses);
+ Assert.assertEquals(1, certificateResponses.size());
+ Assert.assertEquals(certificateResponses.get(0).getSerialNumber(), x509Certificate.getSerialNumber().toString());
+ log.info("SearchCertificates Test Successful");
+ }
+
+ @Test(description = "This test case tests generation of signed Certificate from a CSR")
+ public void testGetSignedCertificateFromCSR() throws KeystoreException {
+ CSRGenerator csrGeneration = new CSRGenerator();
+ BASE64Encoder encoder = new BASE64Encoder();
+ // Generate key pair
+ KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
+ byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
+ X509Certificate signedCertificateFromCSR = managementService.getSignedCertificateFromCSR(encoder.encode(csrData));
+ Assert.assertNotNull(signedCertificateFromCSR);
+ Assert.assertEquals(signedCertificateFromCSR.getType(), CertificateManagementConstants.X_509);
+ log.info("GetSignedCertificateFromCSR Test Successful");
+ }
+
+ @Test(description = "This test case tests the extraction of Challenge token from a Certificate")
+ public void testExtractChallengeToken() throws KeystoreException {
+ X509Certificate x509Certificate1 = new DummyCertificate();
+ String token = managementService.extractChallengeToken(x509Certificate1);
+ Assert.assertNotNull(token);
+ Assert.assertEquals(token, DummyCertificate.EXT);
+ log.info("extractChallengeToken Test Successful");
+ }
+
+ @Test(description = "This test case tests saving a list of Certificates in the keystore")
+ public void testSaveCertificate() throws CertificateManagementException, IOException, CertificateException, KeystoreException {
+ File caCert = new File(CA_CERT_PEM);
+ int before = managementService.getCertificates().size();
+ byte[] caBytes = FileUtils.readFileToByteArray(caCert);
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(caBytes));
+ List certificates = new ArrayList<>();
+ org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore =
+ new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
+ certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
+ certificateToStore.setCertificate(cert);
+ certificates.add(certificateToStore);
+ managementService.saveCertificate(certificates);
+ int after = managementService.getCertificates().size();
+ Assert.assertEquals((before + 1), after);
+ log.info("SaveCertificate Test Successful");
+ }
+
+ @Test(description = "This test case tests converting a pem file to X509 Certificate")
+ public void testPemToX509Certificate() throws IOException, KeystoreException {
+ File caCert = new File(CA_CERT_PEM);
+ BASE64Encoder encoder = new BASE64Encoder();
+ byte[] caBytes = FileUtils.readFileToByteArray(caCert);
+ X509Certificate certificate = managementService.pemToX509Certificate(encoder.encode(caBytes));
+ Assert.assertNotNull(certificate);
+ Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("PemToX509Certificate Test Successful");
+ }
+
+ @Test(description = "This test case tests extracting Certificate from the header Signature")
+ public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
+ BASE64Encoder encoder = new BASE64Encoder();
+ //generate and save a certificate in the keystore
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ //Generate CMSdata
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ List list = new ArrayList<>();
+ list.add(x509Certificate);
+ JcaCertStore store = new JcaCertStore(list);
+ generator.addCertificates(store);
+ CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
+ byte[] signature = degenerateSd.getEncoded();
+ X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature));
+ Assert.assertNotNull(certificate);
+ Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("ExtractCertificateFromSignature Test Successful");
+ }
+
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CSRGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CSRGenerator.java
new file mode 100644
index 0000000000..5fa4f7dabd
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CSRGenerator.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.certificate.mgt.core.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
+
+import javax.security.auth.x500.X500Principal;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * Test class for generating a mock CSR request.
+ */
+public class CSRGenerator {
+ private static Log log = LogFactory.getLog(CSRGenerator.class);
+
+ /**
+ * Generate the desired CSR for signing
+ *
+ * @param sigAlg
+ * @param keyPair
+ * @return
+ */
+ public byte[] generateCSR(String sigAlg, KeyPair keyPair) {
+ ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outStream);
+ try {
+ PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
+ new X500Principal("CN=Requested Test Certificate"), keyPair.getPublic());
+ JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
+ ContentSigner signer = csBuilder.build(keyPair.getPrivate());
+ PKCS10CertificationRequest csr = p10Builder.build(signer);
+ return csr.getEncoded();
+ } catch (OperatorCreationException ex) {
+ log.error("Error while Key generation operation", ex);
+ } catch (IOException ex) {
+ log.error("Error while generating CSR,ex");
+ }
+ return new byte[0];
+ }
+
+ /**
+ * Generate the desired keypair
+ *
+ * @param alg
+ * @param keySize
+ * @return
+ */
+ public KeyPair generateKeyPair(String alg, int keySize) {
+ try {
+ KeyPairGenerator keyPairGenerator = null;
+ keyPairGenerator = KeyPairGenerator.getInstance(alg);
+ keyPairGenerator.initialize(keySize);
+ return keyPairGenerator.generateKeyPair();
+ } catch (NoSuchAlgorithmException e) {
+ log.error("The provided algorithm is not found ",e);
+ }
+ return null;
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/DummyCertificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/DummyCertificate.java
new file mode 100644
index 0000000000..f276df4625
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/DummyCertificate.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.certificate.mgt.core.util;
+
+import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
+
+import java.math.BigInteger;
+import java.security.Principal;
+import java.security.PublicKey;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.CertificateException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SignatureException;
+import java.security.NoSuchProviderException;
+import java.security.cert.X509Certificate;
+import java.security.InvalidKeyException;
+import java.util.Date;
+import java.util.Set;
+
+/**
+ * A Mock Certificate class with an extension provided.(Used only to test the extension)
+ */
+public class DummyCertificate extends X509Certificate {
+
+ public static final String EXT = "Dummy extension";
+ public static final String DN = "O=WSO2,OU=Mobile,C=LK,CN=123456789";
+
+ @Override
+ public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException {
+ }
+
+ @Override
+ public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException {
+ }
+
+ @Override
+ public int getVersion() {
+ return 0;
+ }
+
+ @Override
+ public BigInteger getSerialNumber() {
+ return new BigInteger("123456789");
+ }
+
+ @Override
+ public Principal getIssuerDN() {
+ return null;
+ }
+
+ @Override
+ public Principal getSubjectDN() {
+ return new Principal() {
+ @Override
+ public String getName() {
+ return DN;
+ }
+ };
+ }
+
+ @Override
+ public Date getNotBefore() {
+ return null;
+ }
+
+ @Override
+ public Date getNotAfter() {
+ return null;
+ }
+
+ @Override
+ public byte[] getTBSCertificate() throws CertificateEncodingException {
+ return new byte[0];
+ }
+
+ @Override
+ public byte[] getSignature() {
+ return new byte[0];
+ }
+
+ @Override
+ public String getSigAlgName() {
+ return null;
+ }
+
+ @Override
+ public String getSigAlgOID() {
+ return null;
+ }
+
+ @Override
+ public byte[] getSigAlgParams() {
+ return new byte[0];
+ }
+
+ @Override
+ public boolean[] getIssuerUniqueID() {
+ return new boolean[0];
+ }
+
+ @Override
+ public boolean[] getSubjectUniqueID() {
+ return new boolean[0];
+ }
+
+ @Override
+ public boolean[] getKeyUsage() {
+ return new boolean[0];
+ }
+
+ @Override
+ public int getBasicConstraints() {
+ return 0;
+ }
+
+ @Override
+ public byte[] getEncoded() throws CertificateEncodingException {
+ return new byte[0];
+ }
+
+ @Override
+ public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
+ }
+
+ @Override
+ public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
+ }
+
+ @Override
+ public String toString() {
+ return null;
+ }
+
+ @Override
+ public PublicKey getPublicKey() {
+ return null;
+ }
+
+ @Override
+ public boolean hasUnsupportedCriticalExtension() {
+ return false;
+ }
+
+ @Override
+ public Set getCriticalExtensionOIDs() {
+ return null;
+ }
+
+ @Override
+ public Set getNonCriticalExtensionOIDs() {
+ return null;
+ }
+
+ @Override
+ public byte[] getExtensionValue(String oid) {
+ if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_challengePassword.toString())) {
+ return EXT.getBytes();
+ } else {
+ return new byte[0];
+ }
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/TestUtils.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/TestUtils.java
new file mode 100644
index 0000000000..34d6936676
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/TestUtils.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * you may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+public class TestUtils {
+
+ private static final Log log = LogFactory.getLog(TestUtils.class);
+
+ public static void cleanupResources(Connection conn, Statement stmt, ResultSet rs) {
+ if (rs != null) {
+ try {
+ rs.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing result set", e);
+ }
+ }
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing prepared statement", e);
+ }
+ }
+ if (conn != null) {
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing database connection", e);
+ }
+ }
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.der b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.der
new file mode 100644
index 0000000000..72684b1820
Binary files /dev/null and b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.der differ
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/carbon.xml
new file mode 100644
index 0000000000..7f976a58cf
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/carbon.xml
@@ -0,0 +1,655 @@
+
+
+
+
+
+
+
+ ${product.name}
+
+
+ ${product.key}
+
+
+ ${product.version}
+
+
+
+
+
+
+
+
+ local:/${carbon.context}/services/
+
+
+
+
+
+
+ ${default.server.role}
+
+
+
+
+
+
+ org.wso2.carbon
+
+
+ /
+
+
+
+
+
+
+
+
+ 15
+
+
+
+
+
+
+
+
+ 0
+
+
+
+
+ 9999
+
+ 11111
+
+
+
+
+
+ 10389
+
+ 8000
+
+
+
+
+
+ 10500
+
+
+
+
+
+
+ org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory
+
+
+
+
+
+
+
+
+ java
+
+
+
+
+
+
+
+
+
+ false
+
+
+ false
+
+
+ 600
+
+
+
+ false
+
+
+
+
+
+
+
+ 30
+
+
+
+
+
+
+
+
+ 15
+
+
+
+
+
+ ${carbon.home}/repository/deployment/server/
+
+
+ 15
+
+
+ ${carbon.home}/repository/conf/axis2/axis2.xml
+
+
+ 30000
+
+
+ ${carbon.home}/repository/deployment/client/
+
+ ${carbon.home}/repository/conf/axis2/axis2_client.xml
+
+ true
+
+
+
+
+
+
+
+
+
+ admin
+ Default Administrator Role
+
+
+ user
+ Default User Role
+
+
+
+
+
+
+
+
+
+
+
+ ${carbon.home}/repository/resources/security/wso2carbon.jks
+
+ JKS
+
+ wso2carbon
+
+ wso2carbon
+
+ wso2carbon
+
+
+
+
+
+ ${carbon.home}/repository/resources/security/client-truststore.jks
+
+ JKS
+
+ wso2carbon
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ UserManager
+
+
+ false
+
+
+
+
+
+
+ ${carbon.home}/tmp/work
+
+
+
+
+
+ true
+
+
+ 10
+
+
+ 30
+
+
+
+
+
+ 100
+
+
+
+ keystore
+ certificate
+ *
+
+ org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor
+
+
+
+
+ jarZip
+
+ org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor
+
+
+
+ dbs
+
+ org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor
+
+
+
+ tools
+
+ org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor
+
+
+
+ toolsAny
+
+ org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor
+
+
+
+
+
+
+ - info
+ org.wso2.carbon.core.transports.util.InfoProcessor
+
+
+ - wsdl
+ org.wso2.carbon.core.transports.util.Wsdl11Processor
+
+
+ - wsdl2
+ org.wso2.carbon.core.transports.util.Wsdl20Processor
+
+
+ - xsd
+ org.wso2.carbon.core.transports.util.XsdProcessor
+
+
+
+
+
+ false
+ false
+ true
+ svn
+ http://svnrepo.example.com/repos/
+ username
+ password
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ${require.carbon.servlet}
+
+
+
+
+ true
+
+
+
+
+
+
+ default repository
+ ${p2.repo.url}
+
+
+
+
+
+
+
+ true
+
+
+
+
+
+ true
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml
new file mode 100644
index 0000000000..bc996646e1
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml
@@ -0,0 +1,62 @@
+
+
+
+
+
+
+
+ jdbc/DM_DS
+
+
+
+
+ 8
+ 100
+ 20
+ 1000
+
+
+ https://localhost:9443
+ admin
+ admin
+
+
+ org.wso2.carbon.policy.mgt
+ true
+ 60000
+ 5
+ 8
+ 20
+
+ Simple
+
+
+
+ true
+
+
+ true
+ 86400
+
+
+ true
+ 300
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/certificate-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/certificate-config.xml
new file mode 100755
index 0000000000..949c4c2cd4
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/certificate-config.xml
@@ -0,0 +1,36 @@
+
+
+
+
+
+ ${carbon.home}/repository/conf/security/wso2certs.jks
+
+ JKS
+
+ wso2carbon
+
+ cacert
+
+ cacert
+
+ racert
+
+ racert
+
+
\ No newline at end of file
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml
new file mode 100644
index 0000000000..40b7e24343
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml
@@ -0,0 +1,85 @@
+
+
+
+
+ org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader
+
+
+
+
+
+ WSO2_CARBON_DB
+ The datasource used for registry and user manager
+
+ jdbc/WSO2CarbonDB
+
+
+
+ jdbc:h2:repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000
+ wso2carbon
+ wso2carbon
+ org.h2.Driver
+ 50
+ 60000
+ true
+ SELECT 1
+ 30000
+ false
+
+
+
+
+
+
+
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/log4j.properties b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/log4j.properties
new file mode 100644
index 0000000000..d1014499f9
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/log4j.properties
@@ -0,0 +1,165 @@
+#
+# Copyright 2017 WSO2, Inc. (http://wso2.com)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+#
+# This is the log4j configuration file used by WSO2 Carbon
+#
+# IMPORTANT : Please do not remove or change the names of any
+# of the Appenders defined here. The layout pattern & log file
+# can be changed using the WSO2 Carbon Management Console, and those
+# settings will override the settings in this file.
+#
+
+log4j.rootLogger=INFO, CARBON_CONSOLE, CARBON_LOGFILE, CARBON_MEMORY, CARBON_SYS_LOG
+
+log4j.logger.AUDIT_LOG=INFO, AUDIT_LOGFILE
+log4j.logger.org.apache.axis2.wsdl.codegen.writer.PrettyPrinter=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.axis2.clustering=INFO, CARBON_CONSOLE, CARBON_LOGFILE
+log4j.logger.org.apache=INFO, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.catalina=WARN
+log4j.logger.org.apache.tomcat=WARN
+log4j.logger.org.wso2.carbon.apacheds=WARN
+log4j.logger.org.apache.directory.server.ldap=ERROR
+log4j.logger.org.apache.directory.server.core.event=WARN
+log4j.logger.com.atomikos=INFO,ATOMIKOS
+log4j.logger.org.quartz=WARN
+log4j.logger.org.apache.jackrabbit.webdav=WARN
+log4j.logger.org.apache.juddi=ERROR
+log4j.logger.org.apache.commons.digester.Digester=WARN
+log4j.logger.org.apache.jasper.compiler.TldLocationsCache=WARN
+log4j.logger.org.apache.qpid=WARN
+log4j.logger.org.apache.qpid.server.Main=INFO
+log4j.logger.qpid.message=WARN
+log4j.logger.qpid.message.broker.listening=INFO
+log4j.logger.org.apache.tiles=WARN
+log4j.logger.org.apache.commons.httpclient=ERROR
+log4j.logger.org.apache.coyote=WARN
+log4j.logger.org.apache.solr=ERROR
+log4j.logger.me.prettyprint.cassandra.hector.TimingLogger=ERROR
+log4j.logger.org.wso2=INFO
+log4j.logger.org.apache.axis2.enterprise=FATAL, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.opensaml.xml=WARN, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.shared.ldap=WARN, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.ldap.handlers=WARN, CARBON_LOGFILE, CARBON_MEMORY
+#Following are to remove false error messages from startup (IS)
+log4j.logger.org.apache.directory.shared.ldap.entry.DefaultServerAttribute=FATAL, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.core.DefaultDirectoryService=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.shared.ldap.ldif.LdifReader=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.ldap.LdapProtocolHandler=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.core=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.ldap.LdapSession=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+#Hive Related Log configurations
+log4j.logger.DataNucleus=ERROR
+log4j.logger.Datastore=ERROR
+log4j.logger.Datastore.Schema=ERROR
+log4j.logger.JPOX.Datastore=ERROR
+log4j.logger.JPOX.Plugin=ERROR
+log4j.logger.JPOX.MetaData=ERROR
+log4j.logger.JPOX.Query=ERROR
+log4j.logger.JPOX.General=ERROR
+log4j.logger.JPOX.Enhancer=ERROR
+log4j.logger.org.apache.hadoop.hive=WARN
+log4j.logger.hive=WARN
+log4j.logger.ExecMapper=WARN
+log4j.logger.ExecReducer=WARN
+log4j.logger.net.sf.ehcache.config.ConfigurationFactory=ERROR
+
+log4j.logger.trace.messages=TRACE,CARBON_TRACE_LOGFILE
+
+log4j.additivity.org.apache.axis2.clustering=false
+log4j.additivity.com.atomikos=false
+log4j.additivity.org.apache=false
+
+# CARBON_CONSOLE is set to be a ConsoleAppender using a PatternLayout.
+log4j.appender.CARBON_CONSOLE=org.wso2.carbon.utils.logging.appenders.CarbonConsoleAppender
+log4j.appender.CARBON_CONSOLE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+# ConversionPattern will be overridden by the configuration setting in the DB
+log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d] %P%5p {%c} - %x %m%n
+log4j.appender.CARBON_CONSOLE.layout.TenantPattern=%U%@%D[%T]
+log4j.appender.CARBON_CONSOLE.threshold=DEBUG
+
+# CARBON_MEMORY is set to be a MemoryAppender using a PatternLayout.
+log4j.appender.CARBON_MEMORY=org.wso2.carbon.utils.logging.appenders.MemoryAppender
+log4j.appender.CARBON_MEMORY.layout=org.apache.log4j.PatternLayout
+log4j.appender.CARBON_MEMORY.bufferSize=200
+# ConversionPattern will be overridden by the configuration setting in the DB
+#log4j.appender.CARBON_MEMORY.layout.ConversionPattern=[%d] %5p - %x %m {%c}%n
+log4j.appender.CARBON_MEMORY.layout.ConversionPattern=[%d] %5p {%c} - %x %m %n
+log4j.appender.CARBON_MEMORY.threshold=DEBUG
+
+
+# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout.
+log4j.appender.CARBON_LOGFILE=org.wso2.carbon.utils.logging.appenders.CarbonDailyRollingFileAppender
+# Log file will be overridden by the configuration setting in the DB
+# This path should be relative to WSO2 Carbon Home
+log4j.appender.CARBON_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon${instance.log}.log
+log4j.appender.CARBON_LOGFILE.Append=true
+log4j.appender.CARBON_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+# ConversionPattern will be overridden by the configuration setting in the DB
+log4j.appender.CARBON_LOGFILE.layout.ConversionPattern=TID: [%T] [%S] [%d] %P%5p {%c} - %x %m %n
+log4j.appender.CARBON_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
+log4j.appender.CARBON_LOGFILE.threshold=DEBUG
+
+log4j.appender.CARBON_SYS_LOG = org.apache.log4j.net.SyslogAppender
+log4j.appender.CARBON_SYS_LOG.layout=org.apache.log4j.PatternLayout
+log4j.appender.CARBON_SYS_LOG.layout.ConversionPattern=[%d] %5p {%c} - %x %m %n
+log4j.appender.CARBON_SYS_LOG.SyslogHost=localhost
+log4j.appender.CARBON_SYS_LOG.Facility=USER
+log4j.appender.CARBON_SYS_LOG.threshold=DEBUG
+
+# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT
+log4j.appender.LOGEVENT=org.wso2.carbon.logging.service.appender.LogEventAppender
+log4j.appender.LOGEVENT.url=tcp://10.100.3.103:7611
+log4j.appender.LOGEVENT.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+log4j.appender.LOGEVENT.columnList=%T,%S,%A,%d,%c,%p,%m,%H,%I,%Stacktrace
+log4j.appender.LOGEVENT.userName=admin
+log4j.appender.LOGEVENT.password=admin
+#log4j.appender.LOGEVENT.password=secretAlias:Log4j.Appender.LOGEVENT.Password
+
+# Appender config to CARBON_TRACE_LOGFILE
+log4j.appender.CARBON_TRACE_LOGFILE=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.CARBON_TRACE_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon-trace-messages${instance.log}.log
+log4j.appender.CARBON_TRACE_LOGFILE.Append=true
+log4j.appender.CARBON_TRACE_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+log4j.appender.CARBON_TRACE_LOGFILE.layout.ConversionPattern=[%d] %P%5p {%c} - %x %m %n
+log4j.appender.CARBON_TRACE_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
+log4j.appender.CARBON_TRACE_LOGFILE.threshold=TRACE
+log4j.additivity.trace.messages=false
+
+# Appender config to AUDIT_LOGFILE
+log4j.appender.AUDIT_LOGFILE=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.AUDIT_LOGFILE.File=${carbon.home}/repository/logs/audit.log
+log4j.appender.AUDIT_LOGFILE.Append=true
+log4j.appender.AUDIT_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+log4j.appender.AUDIT_LOGFILE.layout.ConversionPattern=[%d] %P%5p {%c}- %x %m %n
+log4j.appender.AUDIT_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
+log4j.appender.AUDIT_LOGFILE.threshold=INFO
+log4j.additivity.AUDIT_LOG=false
+
+# Appender config to send Atomikos transaction logs to new log file tm.out.
+log4j.appender.ATOMIKOS = org.apache.log4j.RollingFileAppender
+log4j.appender.ATOMIKOS.File = repository/logs/tm.out
+log4j.appender.ATOMIKOS.Append = true
+log4j.appender.ATOMIKOS.layout = org.apache.log4j.PatternLayout
+log4j.appender.ATOMIKOS.layout.ConversionPattern=%p %t %c - %m%n
+
+# This file is used to override the default logger settings, and is used to remove unwanted logs from Shindig appearing on the console.
+
+# Specification of Handler used by Console Logger
+handlers=java.util.logging.ConsoleHandler
+
+# Replacing default INFO level with SEVERE
+java.util.logging.ConsoleHandler.level=SEVERE
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/security/wso2certs.jks b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/security/wso2certs.jks
new file mode 100644
index 0000000000..c1e9ace3c2
Binary files /dev/null and b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/security/wso2certs.jks differ
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
index e19786b861..0e996abca5 100755
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
@@ -1,8 +1,25 @@
+
- ${carbon.home}/repository/resources/security/wso2certs.jks
+ ${carbon.home}/repository/resources/wso2certs.jks
JKS
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/data-source-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/data-source-config.xml
new file mode 100644
index 0000000000..d9be5b3ac0
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/data-source-config.xml
@@ -0,0 +1,33 @@
+
+
+
+
+ jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true
+ org.h2.Driver
+ wso2carbon
+ wso2carbon
+
+
+
+
+
+
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/log4j.properties b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/log4j.properties
deleted file mode 100644
index 2143753b40..0000000000
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# Copyright 2015 WSO2, Inc. (http://wso2.com)
-#
-# WSO2 Inc. licenses this file to you under the Apache License,
-# version 2.0 (the "License"); you may not use this file except
-# in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-#
-# This is the log4j configuration file used by WSO2 Carbon
-#
-# IMPORTANT : Please do not remove or change the names of any
-# of the Appenders defined here. The layout pattern & log file
-# can be changed using the WSO2 Carbon Management Console, and those
-# settings will override the settings in this file.
-#
-
-log4j.rootLogger=INFO, STD_OUT
-
-# Redirect log messages to console
-log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
-log4j.appender.STD_OUT.Target=System.out
-log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout
-log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/sql/h2.sql b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/sql/h2.sql
new file mode 100644
index 0000000000..044898f912
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/sql/h2.sql
@@ -0,0 +1,25 @@
+--
+-- Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+--
+-- WSO2 Inc. licenses this file to you under the Apache License,
+-- Version 2.0 (the "License"); you may not use this file except
+-- in compliance with the License.
+-- You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied. See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
+ ID INTEGER auto_increment NOT NULL,
+ SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
+ CERTIFICATE BLOB DEFAULT NULL,
+ TENANT_ID INTEGER DEFAULT 0,
+ USERNAME VARCHAR(500) DEFAULT NULL,
+ PRIMARY KEY (ID)
+);
\ No newline at end of file
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml
index d05fefdb8a..b76295f108 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml
@@ -1,12 +1,33 @@
+
+
-
+
+
+
-
\ No newline at end of file
+
+