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
new file mode 100644
index 0000000000..72647601ae
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
@@ -0,0 +1,152 @@
+
+
+
+
+
+ org.wso2.carbon.devicemgt
+ certificate-mgt
+ 0.9.2-SNAPSHOT
+ ../pom.xml
+
+
+ 4.0.0
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.certificate.mgt.core
+ 0.9.2-SNAPSHOT
+ bundle
+ WSO2 Carbon - Certificate Management Core
+ WSO2 Carbon - Certificate Management Core
+ http://wso2.org
+
+
+
+
+ org.apache.felix
+ maven-scr-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 1.4.0
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ Device Management Core Bundle
+ org.wso2.carbon.certificate.mgt.core.internal
+
+ org.osgi.framework,
+ org.osgi.service.component,
+ org.apache.commons.logging,
+ javax.security.auth.x500,
+ javax.xml.parsers,
+ org.apache.commons.codec.binary,
+ org.bouncycastle.asn1,
+ org.bouncycastle.asn1.x500,
+ org.bouncycastle.asn1.x509,
+ org.bouncycastle.cert,
+ org.bouncycastle.cert.jcajce,
+ org.bouncycastle.cms,
+ org.bouncycastle.jce.provider,
+ org.bouncycastle.operator,
+ org.bouncycastle.operator.jcajce,
+ org.bouncycastle.pkcs,
+ org.bouncycastle.util,
+ org.jscep.message,
+ org.jscep.transaction,
+ org.w3c.dom,
+ org.xml.sax
+
+
+ !org.wso2.carbon.certificate.mgt.core.internal.*,
+ org.wso2.carbon.certificate.mgt.core.dto.*,
+ org.wso2.carbon.certificate.mgt.core.exception.*,
+ org.wso2.carbon.certificate.mgt.core.impl.*,
+ org.wso2.carbon.certificate.mgt.core.service.*,
+ org.wso2.carbon.certificate.mgt.core.util.*
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.18
+
+
+ file:src/test/resources/log4j.properties
+
+
+ src/test/resources/testng.xml
+
+
+
+
+
+
+
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi.services
+
+
+ org.testng
+ testng
+
+
+ org.wso2.carbon
+ org.wso2.carbon.logging
+
+
+ org.bouncycastle.wso2
+ bcprov-jdk15on
+
+
+ org.bouncycastle.wso2
+ bcpkix-jdk15on
+
+
+ org.bouncycastle.wso2
+ bcmail-jdk15on
+
+
+ com.google.code.jscep.wso2
+ jscep
+
+
+ commons-codec.wso2
+ commons-codec
+
+
+ commons-io.wso2
+ commons-io
+
+
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CAStatus.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CAStatus.java
new file mode 100755
index 0000000000..e3439c17d1
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CAStatus.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.dto;
+
+public enum CAStatus {
+
+ CA_CERT_FAILED,
+ CA_CERT_RECEIVED,
+ CA_RA_CERT_RECEIVED
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/SCEPResponse.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/SCEPResponse.java
new file mode 100755
index 0000000000..e3aa25c805
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/SCEPResponse.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.dto;
+
+public class SCEPResponse {
+
+ private byte[] encodedResponse;
+ private CAStatus resultCriteria;
+
+ public byte[] getEncodedResponse() {
+ return encodedResponse;
+ }
+
+ public void setEncodedResponse(byte[] encodedResponse) {
+ this.encodedResponse = encodedResponse;
+ }
+
+ public CAStatus getResultCriteria() {
+ return resultCriteria;
+ }
+
+ public void setResultCriteria(CAStatus resultCriteria) {
+ this.resultCriteria = resultCriteria;
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/KeystoreException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/KeystoreException.java
new file mode 100644
index 0000000000..ddc61c9699
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/KeystoreException.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.exception;
+
+public class KeystoreException extends Exception {
+
+ private static final long serialVersionUID = -8935640983869122660L;
+ private String errorMessage;
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public KeystoreException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
+
+ public KeystoreException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
+
+ public KeystoreException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
+
+ public KeystoreException() {
+ super();
+ }
+
+ public KeystoreException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java
new file mode 100755
index 0000000000..a1ddb3c20e
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java
@@ -0,0 +1,484 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.impl;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.asn1.x509.X509Extension;
+import org.bouncycastle.cert.CertIOException;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaCertStore;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.cms.CMSAbsentContent;
+import org.bouncycastle.cms.CMSException;
+import org.bouncycastle.cms.CMSSignedData;
+import org.bouncycastle.cms.CMSSignedDataGenerator;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.util.Store;
+import org.jscep.message.CertRep;
+import org.jscep.message.MessageDecodingException;
+import org.jscep.message.MessageEncodingException;
+import org.jscep.message.PkcsPkiEnvelopeDecoder;
+import org.jscep.message.PkcsPkiEnvelopeEncoder;
+import org.jscep.message.PkiMessage;
+import org.jscep.message.PkiMessageDecoder;
+import org.jscep.message.PkiMessageEncoder;
+import org.jscep.transaction.FailInfo;
+import org.jscep.transaction.Nonce;
+import org.jscep.transaction.TransactionId;
+import org.wso2.carbon.certificate.mgt.core.dto.CAStatus;
+import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+import org.wso2.carbon.certificate.mgt.core.util.CommonUtil;
+import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
+
+import javax.security.auth.x500.X500Principal;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.SignatureException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.X509Certificate;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+
+public class CertificateGenerator {
+
+ private static final Log log = LogFactory.getLog(CertificateGenerator.class);
+
+ public List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException {
+
+ if (ca == null) {
+ throw new KeystoreException("CA certificate is mandatory");
+ }
+
+ if (ra == null) {
+ throw new KeystoreException("RA certificate is mandatory");
+ }
+
+ List certificateList = new ArrayList();
+ InputStream caInputStream = null;
+ InputStream raInputStream = null;
+
+ try {
+ CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509);
+ caInputStream = new ByteArrayInputStream(ca);
+ raInputStream = new ByteArrayInputStream(ra);
+
+ X509Certificate caCert = (X509Certificate) certificateFactory.generateCertificate(caInputStream);
+ X509Certificate raCert = (X509Certificate) certificateFactory.generateCertificate(raInputStream);
+
+ certificateList.add(caCert);
+ certificateList.add(raCert);
+ } catch (CertificateException e) {
+ String errorMsg = "Error occurred while fetching root certificates";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } finally {
+ if (caInputStream != null) {
+ try {
+ caInputStream.close();
+ } catch (IOException e) {
+ log.error("Error occurred when closing CA input stream");
+ }
+ }
+
+ if (raInputStream != null) {
+ try {
+ raInputStream.close();
+ } catch (IOException e) {
+ log.error("Error occurred when closing RA input stream");
+ }
+ }
+ }
+
+ return certificateList;
+ }
+
+ public X509Certificate generateX509Certificate() throws KeystoreException {
+
+ CommonUtil commonUtil = new CommonUtil();
+ Date validityBeginDate = commonUtil.getValidityStartDate();
+ Date validityEndDate = commonUtil.getValidityEndDate();
+
+ Security.addProvider(new BouncyCastleProvider());
+
+ try {
+ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
+ ConfigurationUtil.RSA, ConfigurationUtil.PROVIDER);
+ keyPairGenerator.initialize(ConfigurationUtil.RSA_KEY_LENGTH, new SecureRandom());
+ KeyPair pair = keyPairGenerator.generateKeyPair();
+ X500Principal principal = new X500Principal(ConfigurationUtil.DEFAULT_PRINCIPAL);
+ BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
+
+ X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
+ principal, serial, validityBeginDate, validityEndDate,
+ principal, pair.getPublic());
+ ContentSigner contentSigner = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA)
+ .setProvider(ConfigurationUtil.PROVIDER).build(
+ pair.getPrivate());
+ X509Certificate certificate = new JcaX509CertificateConverter()
+ .setProvider(ConfigurationUtil.PROVIDER).getCertificate(
+ certificateBuilder.build(contentSigner));
+
+ // cert.checkValidity();
+
+ certificate.verify(certificate.getPublicKey());
+
+ saveCertInKeyStore(certificate);
+
+ return certificate;
+ } catch (NoSuchAlgorithmException e) {
+ String errorMsg = "No such algorithm found when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (NoSuchProviderException e) {
+ String errorMsg = "No such provider found when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (OperatorCreationException e) {
+ String errorMsg = "Issue in operator creation when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CertificateExpiredException e) {
+ String errorMsg = "Certificate expired after generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CertificateNotYetValidException e) {
+ String errorMsg = "Certificate not yet valid when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CertificateException e) {
+ String errorMsg = "Certificate issue occurred when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (InvalidKeyException e) {
+ String errorMsg = "Invalid key used when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (SignatureException e) {
+ String errorMsg = "Signature related issue occurred when generating certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+
+ public byte[] getPKIMessage(InputStream inputStream) throws KeystoreException {
+
+ try {
+ CMSSignedData signedData = new CMSSignedData(inputStream);
+ Store reqStore = signedData.getCertificates();
+ @SuppressWarnings("unchecked")
+ Collection reqCerts = reqStore.getMatches(null);
+
+ KeyStoreReader keyStoreReader = new KeyStoreReader();
+ PrivateKey privateKeyRA = keyStoreReader.getRAPrivateKey();
+ PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
+ X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate();
+ X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
+
+ CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509);
+ X509CertificateHolder holder = reqCerts.iterator().next();
+ ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
+ X509Certificate reqCert = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream);
+
+ PkcsPkiEnvelopeDecoder envelopeDecoder = new PkcsPkiEnvelopeDecoder(certRA, privateKeyRA);
+ PkiMessageDecoder messageDecoder = new PkiMessageDecoder(reqCert, envelopeDecoder);
+ PkiMessage> pkiMessage = messageDecoder.decode(signedData);
+ Object msgData = pkiMessage.getMessageData();
+
+ Nonce senderNonce = Nonce.nextNonce();
+ TransactionId transId = pkiMessage.getTransactionId();
+ Nonce recipientNonce = pkiMessage.getSenderNonce();
+ CertRep certRep;
+
+ PKCS10CertificationRequest certRequest = (PKCS10CertificationRequest) msgData;
+ X509Certificate generatedCert = generateCertificateFromCSR(
+ privateKeyCA, certRequest, certCA.getIssuerX500Principal().getName());
+
+ List issued = new ArrayList();
+ issued.add(generatedCert);
+
+ if (issued.size() == 0) {
+ certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
+ } else {
+ CMSSignedData messageData = getMessageData(issued);
+ certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
+ }
+
+ PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, ConfigurationUtil.DES_EDE);
+ PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder);
+ CMSSignedData cmsSignedData = encoder.encode(certRep);
+
+ return cmsSignedData.getEncoded();
+
+ } catch (CertificateException e) {
+ String errorMsg = "Certificate issue occurred when generating getPKIMessage";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (MessageEncodingException e) {
+ String errorMsg = "Message encoding issue occurred when generating getPKIMessage";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (IOException e) {
+ String errorMsg = "Input output issue occurred when generating getPKIMessage";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (MessageDecodingException e) {
+ String errorMsg = "Message decoding issue occurred when generating getPKIMessage";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CMSException e) {
+ String errorMsg = "CMS issue occurred when generating getPKIMessage";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+
+ public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
+ PKCS10CertificationRequest request,
+ String issueSubject)
+ throws KeystoreException {
+
+ CommonUtil commonUtil = new CommonUtil();
+ Date validityBeginDate = commonUtil.getValidityStartDate();
+ Date validityEndDate = commonUtil.getValidityEndDate();
+
+ X500Name certSubject = request.getSubject();
+
+ if (certSubject == null) {
+ certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
+ } else {
+ org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs();
+
+ if (rdn == null || rdn.length == 0) {
+ certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
+ }
+ }
+
+ X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
+ new X500Name(issueSubject), BigInteger.valueOf(System.currentTimeMillis()),
+ validityBeginDate, validityEndDate, certSubject, request.getSubjectPublicKeyInfo());
+
+ ContentSigner sigGen;
+ X509Certificate issuedCert;
+ try {
+ certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(
+ KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
+ sigGen = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA)
+ .setProvider(ConfigurationUtil.PROVIDER).build(privateKey);
+ issuedCert = new JcaX509CertificateConverter().setProvider(
+ ConfigurationUtil.PROVIDER).getCertificate(
+ certificateBuilder.build(sigGen));
+
+ saveCertInKeyStore(issuedCert);
+ } catch (CertIOException e) {
+ String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (OperatorCreationException e) {
+ String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CertificateException e) {
+ String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+
+ return issuedCert;
+ }
+
+ private CMSSignedData getMessageData(final List certs) throws KeystoreException {
+
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ JcaCertStore store;
+ try {
+ store = new JcaCertStore(certs);
+ generator.addCertificates(store);
+
+ return generator.generate(new CMSAbsentContent());
+ } catch (CertificateEncodingException e) {
+ String errorMsg = "Certificate encoding issue occurred when generating getMessageData";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CMSException e) {
+ String errorMsg = "Message decoding issue occurred when generating getMessageData";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+
+ private PrivateKey getSignerKey(String signerPrivateKeyPath) throws KeystoreException {
+
+ File file = new File(signerPrivateKeyPath);
+ FileInputStream fis;
+
+ try {
+ fis = new FileInputStream(file);
+ DataInputStream dis = new DataInputStream(fis);
+ byte[] keyBytes = new byte[(int) file.length()];
+ dis.readFully(keyBytes);
+ dis.close();
+
+ String temp = new String(keyBytes);
+ String privateKeyPEM = temp.replace(
+ ConfigurationUtil.RSA_PRIVATE_KEY_BEGIN_TEXT, ConfigurationUtil.EMPTY_TEXT);
+ privateKeyPEM = privateKeyPEM
+ .replace(ConfigurationUtil.RSA_PRIVATE_KEY_END_TEXT, ConfigurationUtil.EMPTY_TEXT);
+
+ byte[] decoded = Base64.decodeBase64(privateKeyPEM);
+ PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(decoded);
+ KeyFactory keyFactory = KeyFactory.getInstance(ConfigurationUtil.RSA);
+
+ return keyFactory.generatePrivate(encodedKeySpec);
+ } catch (FileNotFoundException e) {
+ String errorMsg = "Private key file not found in getSignerKey";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (IOException e) {
+ String errorMsg = "Input output issue in getSignerKey";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (NoSuchAlgorithmException e) {
+ String errorMsg = "Algorithm not not found in getSignerKey";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (InvalidKeySpecException e) {
+ String errorMsg = "Invalid key found in getSignerKey";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+
+ private X509Certificate getSigner(String signerCertificatePath) throws KeystoreException {
+
+ X509Certificate certificate;
+ try {
+ CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509);
+ certificate = (X509Certificate) certificateFactory.generateCertificate(
+ new FileInputStream(signerCertificatePath));
+
+ return certificate;
+ } catch (CertificateException e) {
+ String errorMsg = "Certificate related issue occurred in getSigner";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (FileNotFoundException e) {
+ String errorMsg = "Signer certificate path not found in getSigner";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+
+ public SCEPResponse getCACert() throws KeystoreException {
+
+ try {
+ SCEPResponse scepResponse = new SCEPResponse();
+ KeyStoreReader keyStoreReader = new KeyStoreReader();
+
+ byte[] caBytes = keyStoreReader.getCACertificate().getEncoded();
+ byte[] raBytes = keyStoreReader.getRACertificate().getEncoded();
+
+ final List certs = getRootCertificates(caBytes, raBytes);
+
+ byte[] bytes;
+ if (certs.size() == 0) {
+ scepResponse.setResultCriteria(CAStatus.CA_CERT_FAILED);
+ bytes = new byte[0];
+ } else if (certs.size() == 1) {
+ scepResponse.setResultCriteria(CAStatus.CA_CERT_RECEIVED);
+ bytes = certs.get(0).getEncoded();
+ } else {
+ scepResponse.setResultCriteria(CAStatus.CA_RA_CERT_RECEIVED);
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ JcaCertStore store = new JcaCertStore(certs);
+ generator.addCertificates(store);
+ CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
+ bytes = degenerateSd.getEncoded();
+ }
+ scepResponse.setEncodedResponse(bytes);
+
+ return scepResponse;
+ } catch (CertificateEncodingException e) {
+ String errorMsg = "Certificate encoding issue occurred in getCACert";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CMSException e) {
+ String errorMsg = "CMS issue occurred in getCACert";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (IOException e) {
+ String errorMsg = "Input output issue occurred in getCACert";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+
+ private void saveCertInKeyStore(X509Certificate certificate) throws KeystoreException {
+
+ if (certificate == null) {
+ return;
+ }
+
+ try {
+ KeyStoreReader keyStoreReader = new KeyStoreReader();
+ KeyStore keyStore = keyStoreReader.loadCertificateKeyStore();
+ keyStore.setCertificateEntry(certificate.getSerialNumber().toString(), certificate);
+
+ keyStoreReader.saveCertificateKeyStore(keyStore);
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeySKeyStoreException occurred when saving the generated certificate";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java
new file mode 100755
index 0000000000..f714a4746b
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.impl;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+
+public class KeyStoreReader {
+
+ private static final Log log = LogFactory.getLog(KeyStoreReader.class);
+
+ private KeyStore loadKeyStore(String configEntryKeyStoreType, String configEntryKeyStorePath,
+ String configEntryKeyStorePassword) throws KeystoreException {
+
+ InputStream inputStream = null;
+ KeyStore keystore;
+
+ try {
+ keystore = KeyStore.getInstance(ConfigurationUtil.getConfigEntry(configEntryKeyStoreType));
+ inputStream = new FileInputStream(ConfigurationUtil.getConfigEntry(configEntryKeyStorePath));
+ keystore.load(inputStream, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray());
+
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeyStore issue occurred when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (FileNotFoundException e) {
+ String errorMsg = "KeyStore file not found when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (NoSuchAlgorithmException e) {
+ String errorMsg = "Algorithm not found when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CertificateException e) {
+ String errorMsg = "CertificateException when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (IOException e) {
+ String errorMsg = "Input output issue occurred when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } finally {
+ try {
+ if (inputStream != null) {
+ inputStream.close();
+ }
+ } catch (IOException e) {
+ log.error("Error closing KeyStore input stream", e);
+ }
+ }
+
+ return keystore;
+ }
+
+ private synchronized void saveKeyStore(KeyStore keyStore, String configEntryKeyStorePath,
+ String configEntryKeyStorePassword) throws KeystoreException {
+
+ FileOutputStream outputStream = null;
+
+ try {
+ outputStream = new FileOutputStream(
+ ConfigurationUtil.getConfigEntry(configEntryKeyStorePath));
+ keyStore.store(outputStream, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray());
+ outputStream.close();
+
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeyStore issue occurred when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (FileNotFoundException e) {
+ String errorMsg = "KeyStore file not found when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (NoSuchAlgorithmException e) {
+ String errorMsg = "Algorithm not found when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (CertificateException e) {
+ String errorMsg = "CertificateException when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (IOException e) {
+ String errorMsg = "Input output issue occurred when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } finally {
+ try {
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ } catch (IOException e) {
+ log.error("Error closing KeyStore output stream", e);
+ }
+ }
+ }
+
+
+ KeyStore loadCertificateKeyStore() throws KeystoreException {
+ return loadKeyStore(ConfigurationUtil.CERTIFICATE_KEYSTORE, ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE,
+ ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD);
+ }
+
+ void saveCertificateKeyStore(KeyStore keyStore) throws KeystoreException {
+ saveKeyStore(keyStore, ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE,
+ ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD);
+ }
+
+ public Certificate getCACertificate() throws KeystoreException {
+
+ KeyStore keystore = loadCertificateKeyStore();
+ Certificate caCertificate;
+
+ try {
+ caCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.CA_CERT_ALIAS));
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeyStore issue occurred when loading KeyStore";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+
+ if (caCertificate == null) {
+ throw new KeystoreException("CA certificate not found in KeyStore");
+ }
+
+ return caCertificate;
+ }
+
+ PrivateKey getCAPrivateKey() throws KeystoreException {
+
+ KeyStore keyStore = loadCertificateKeyStore();
+ PrivateKey caPrivateKey;
+ try {
+ caPrivateKey = (PrivateKey) (keyStore.getKey(
+ ConfigurationUtil.getConfigEntry(ConfigurationUtil.CA_CERT_ALIAS),
+ ConfigurationUtil.getConfigEntry(ConfigurationUtil.KEYSTORE_CA_CERT_PRIV_PASSWORD).toCharArray()));
+ } catch (UnrecoverableKeyException e) {
+ String errorMsg = "Key is unrecoverable when retrieving CA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeyStore issue occurred when retrieving CA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (NoSuchAlgorithmException e) {
+ String errorMsg = "Algorithm not found when retrieving CA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+
+ if (caPrivateKey == null) {
+ throw new KeystoreException("CA private key not found in KeyStore");
+ }
+
+ return caPrivateKey;
+ }
+
+ public Certificate getRACertificate() throws KeystoreException {
+
+ KeyStore keystore = loadCertificateKeyStore();
+ Certificate raCertificate;
+ try {
+ raCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.RA_CERT_ALIAS));
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeyStore issue occurred when retrieving RA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+
+ if (raCertificate == null) {
+ throw new KeystoreException("RA certificate not found in KeyStore");
+ }
+
+ return raCertificate;
+ }
+
+ PrivateKey getRAPrivateKey() throws KeystoreException {
+
+ KeyStore keystore = loadCertificateKeyStore();
+ PrivateKey raPrivateKey;
+ try {
+ raPrivateKey = (PrivateKey) (keystore.getKey(
+ ConfigurationUtil.getConfigEntry(ConfigurationUtil.RA_CERT_ALIAS),
+ ConfigurationUtil.getConfigEntry(ConfigurationUtil.KEYSTORE_RA_CERT_PRIV_PASSWORD).toCharArray()));
+ } catch (UnrecoverableKeyException e) {
+ String errorMsg = "Key is unrecoverable when retrieving RA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (KeyStoreException e) {
+ String errorMsg = "KeyStore issue occurred when retrieving RA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ } catch (NoSuchAlgorithmException e) {
+ String errorMsg = "Algorithm not found when retrieving RA private key";
+ log.error(errorMsg, e);
+ throw new KeystoreException(errorMsg, e);
+ }
+
+ if (raPrivateKey == null) {
+ throw new KeystoreException("RA private key not found in KeyStore");
+ }
+
+ return raPrivateKey;
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java
new file mode 100644
index 0000000000..ccf2f77649
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
+import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl;
+
+/**
+ * @scr.component name="org.wso2.carbon.certificate.mgt" immediate="true"
+ */
+public class CertificateManagementServiceComponent {
+
+ private static Log log = LogFactory.getLog(CertificateManagementServiceComponent.class);
+
+ @SuppressWarnings("unused")
+ protected void activate(ComponentContext componentContext) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Initializing certificate management core bundle");
+ }
+
+ BundleContext bundleContext = componentContext.getBundleContext();
+ bundleContext.registerService(CertificateManagementService.class.getName(),
+ CertificateManagementServiceImpl.getInstance(), null);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Certificate management core bundle has been successfully initialized");
+ }
+ } catch (Throwable e) {
+ log.error("Error occurred while initializing certificate management core bundle", e);
+ }
+ }
+
+ @SuppressWarnings("unused")
+ protected void deactivate(ComponentContext componentContext) {
+ //do nothing
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java
new file mode 100644
index 0000000000..c9b1ca5c96
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.service;
+
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+
+import java.io.InputStream;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+public interface CertificateManagementService {
+
+ Certificate getCACertificate() throws KeystoreException;
+
+ Certificate getRACertificate() throws KeystoreException;
+
+ public List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException;
+
+ public X509Certificate generateX509Certificate() throws KeystoreException;
+
+ public SCEPResponse getCACertSCEP() throws KeystoreException;
+
+ public byte[] getCACapsSCEP();
+
+ public byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException;
+
+ public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
+ PKCS10CertificationRequest request,
+ String issueSubject) throws KeystoreException;
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java
new file mode 100644
index 0000000000..a294acbc16
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator;
+import org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader;
+import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
+
+import java.io.InputStream;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+public class CertificateManagementServiceImpl implements CertificateManagementService {
+
+ private static final Log log = LogFactory.getLog(CertificateManagementServiceImpl.class);
+ private static CertificateManagementServiceImpl certificateManagementServiceImpl;
+ private static KeyStoreReader keyStoreReader;
+ private static CertificateGenerator certificateGenerator;
+
+ private CertificateManagementServiceImpl() {}
+
+ public static CertificateManagementServiceImpl getInstance() {
+
+ if (certificateManagementServiceImpl == null) {
+ certificateManagementServiceImpl = new CertificateManagementServiceImpl();
+ keyStoreReader = new KeyStoreReader();
+ certificateGenerator = new CertificateGenerator();
+ }
+ return certificateManagementServiceImpl;
+ }
+
+ public Certificate getCACertificate() throws KeystoreException {
+ return keyStoreReader.getCACertificate();
+ }
+
+ public Certificate getRACertificate() throws KeystoreException {
+ return keyStoreReader.getRACertificate();
+ }
+
+ public List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException {
+ return certificateGenerator.getRootCertificates(ca, ra);
+ }
+
+ public X509Certificate generateX509Certificate() throws KeystoreException {
+ return certificateGenerator.generateX509Certificate();
+ }
+
+ public SCEPResponse getCACertSCEP() throws KeystoreException {
+ return certificateGenerator.getCACert();
+ }
+
+ public byte[] getCACapsSCEP() {
+ return ConfigurationUtil.POST_BODY_CA_CAPS.getBytes();
+ }
+
+ public byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException {
+ return certificateGenerator.getPKIMessage(inputStream);
+ }
+
+ public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
+ PKCS10CertificationRequest request,
+ String issueSubject) throws KeystoreException {
+ return certificateGenerator.generateCertificateFromCSR(privateKey, request, issueSubject);
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java
new file mode 100755
index 0000000000..a149c92569
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.util;
+
+import java.util.Calendar;
+import java.util.Date;
+
+public class CommonUtil {
+
+ public Date getValidityStartDate() {
+ Date targetDate = new Date();
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(targetDate);
+ calendar.add(Calendar.DATE, -2);
+
+ return calendar.getTime();
+ }
+
+ public Date getValidityEndDate() {
+ Date targetDate = new Date();
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(targetDate);
+ calendar.add(Calendar.YEAR, 100);
+
+ return calendar.getTime();
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java
new file mode 100644
index 0000000000..3767d82824
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.certificate.mgt.core.util;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+import org.xml.sax.SAXException;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class ConfigurationUtil {
+
+ public static final String PATH_CERTIFICATE_KEYSTORE = "CertificateKeystoreLocation";
+ public static final String CERTIFICATE_KEYSTORE_PASSWORD = "CertificateKeystorePassword";
+ public static final String KEYSTORE_CA_CERT_PRIV_PASSWORD = "CAPrivateKeyPassword";
+ public static final String KEYSTORE_RA_CERT_PRIV_PASSWORD = "RAPrivateKeyPassword";
+ public static final String CA_CERT_ALIAS = "CACertAlias";
+ public static final String RA_CERT_ALIAS = "RACertAlias";
+ public static final String SIGNATUREALGO = "SHA1withRSA";
+ public static final String PROVIDER = "BC";
+ public static final String KEYSTORE = "Type";
+ public static final String CERTIFICATE_KEYSTORE = "CertificateKeystoreType";
+ public static final String RSA = "RSA";
+ public static final String UTF_8 = "UTF-8";
+ public static final String SHA256_RSA = "SHA256WithRSAEncryption";
+ public static final String X_509 = "X.509";
+ public static final String POST_BODY_CA_CAPS = "POSTPKIOperation\nSHA-1\nDES3\n";
+ public static final String DES_EDE = "DESede";
+ public static final String CONF_LOCATION = "conf.location";
+ private static final String CARBON_HOME = "carbon.home";
+ private static final String CERTIFICATE_CONFIG_XML = "certificate-config.xml";
+ private static final String CARBON_HOME_ENTRY = "${carbon.home}";
+ public static final String DEFAULT_PRINCIPAL = "O=WSO2, OU=Mobile, C=LK";
+ public static final String RSA_PRIVATE_KEY_BEGIN_TEXT = "-----BEGIN RSA PRIVATE KEY-----\n";
+ public static final String RSA_PRIVATE_KEY_END_TEXT = "-----END RSA PRIVATE KEY-----";
+ public static final String EMPTY_TEXT = "";
+ public static final int RSA_KEY_LENGTH = 1024;
+
+
+ private static ConfigurationUtil configurationUtil;
+ private static final String[] certificateConfigEntryNames = { CA_CERT_ALIAS, RA_CERT_ALIAS,
+ CERTIFICATE_KEYSTORE, PATH_CERTIFICATE_KEYSTORE, CERTIFICATE_KEYSTORE_PASSWORD,
+ KEYSTORE_CA_CERT_PRIV_PASSWORD, KEYSTORE_RA_CERT_PRIV_PASSWORD };
+
+ private static Map configMap;
+
+ private static Map readCertificateConfigurations() throws KeystoreException {
+
+ String certConfLocation = System.getProperty(CONF_LOCATION) + File.separator + CERTIFICATE_CONFIG_XML;
+
+ if (configurationUtil == null || configMap == null) {
+
+ configurationUtil = new ConfigurationUtil();
+ configMap = new HashMap();
+
+ Document document;
+ try {
+ File fXmlFile = new File(certConfLocation);
+ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+ document = documentBuilder.parse(fXmlFile);
+ } catch (ParserConfigurationException e) {
+ throw new KeystoreException("Error parsing configuration in certificate-config.xml file");
+ } catch (SAXException e) {
+ throw new KeystoreException("SAX exception in certificate-config.xml file");
+ } catch (IOException e) {
+ throw new KeystoreException("Error reading certificate-config.xml file");
+ }
+
+ for (String configEntry : certificateConfigEntryNames) {
+ NodeList elements = document.getElementsByTagName(configEntry);
+ if (elements != null && elements.getLength() > 0) {
+ configMap.put(configEntry, elements.item(0).getTextContent());
+ }
+ }
+
+ String certKeyStoreLocation = replaceCarbonHomeEnvEntry(configMap.get(PATH_CERTIFICATE_KEYSTORE));
+ if (certKeyStoreLocation != null) {
+ configMap.put(PATH_CERTIFICATE_KEYSTORE, certKeyStoreLocation);
+ }
+ }
+
+ return configMap;
+ }
+
+ public static String getConfigEntry(final String entry) throws KeystoreException {
+
+ Map configurationMap = readCertificateConfigurations();
+ String configValue = configurationMap.get(entry);
+
+ if (configValue == null) {
+ throw new KeystoreException(String.format("Configuration entry %s not available", entry));
+ }
+
+ return configValue.trim();
+ }
+
+ private static String replaceCarbonHomeEnvEntry(String entry) {
+ if (entry != null && entry.toLowerCase().contains(CARBON_HOME_ENTRY)) {
+ return entry.replace(CARBON_HOME_ENTRY, System.getProperty(CARBON_HOME));
+ }
+
+ return null;
+ }
+
+ public static ConfigurationUtil getInstance() {
+ if (configurationUtil == null) {
+ synchronized (ConfigurationUtil.class) {
+ if (configurationUtil == null) {
+ configurationUtil = new ConfigurationUtil();
+ }
+ }
+ }
+ return configurationUtil;
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java
new file mode 100644
index 0000000000..38ea1fda12
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java
@@ -0,0 +1,103 @@
+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.testng.Assert;
+import org.testng.annotations.Test;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+public class CertificateGeneratorTestSuite {
+
+ private static Log log = LogFactory.getLog(CertificateGeneratorTestSuite.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 static final String CA_PRIVATE_KEY_PATH = "src/test/resources/ca_private.key";
+ private static final String CERTIFICATE_CONFIG_PATH = "src/test/resources/certificate-config.xml";
+ private final CertificateGenerator certificateGenerator = new CertificateGenerator();
+
+ @Test
+ public void testGetRootCertificates() {
+ try {
+ File caPemFile = new File(CA_CERT_PEM);
+ File raPemFile = new File(RA_CERT_PEM);
+
+ byte[] ca = FileUtils.readFileToByteArray(caPemFile);
+ byte[] ra = FileUtils.readFileToByteArray(raPemFile);
+
+ List rootCertificates = certificateGenerator.getRootCertificates(ca, ra);
+ Assert.assertNotNull(rootCertificates, "Root certificates retrieved");
+
+ Assert.assertEquals(rootCertificates.get(0).getType(), ConfigurationUtil.X_509);
+ Assert.assertEquals(rootCertificates.get(1).getType(), ConfigurationUtil.X_509);
+ } catch (IOException e) {
+ Assert.fail("Error reading byte streams for CA and RA ", e);
+ } catch (KeystoreException e) {
+ Assert.fail("Error retrieving root certificates ", e);
+ }
+ }
+
+// @Test
+// public void testGenerateX509Certificate() {
+// try {
+// System.setProperty(ConfigurationUtil.CONF_LOCATION, CERTIFICATE_CONFIG_PATH);
+// X509Certificate certificate = certificateGenerator.generateX509Certificate();
+//
+// Assert.assertNotNull(certificate, "Certificate received");
+// Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509);
+// } catch (KeystoreException e) {
+// Assert.fail("Error occurred while generating X509 certificate ", e);
+// }
+// }
+
+// @Test
+// public void testGetPKIMessage() {
+// try {
+// byte[] pkiMessage = certificateGenerator.getPKIMessage(null);
+// } catch (IOSEnrollmentException e) {
+// Assert.fail("Error occurred while retrieving PKI Message ", e);
+// }
+// }
+
+// @Test
+// public void testGenerateCertificateFromCSR() {
+// try {
+// X509Certificate certificate = certificateGenerator.generateX509Certificate();
+//
+// Assert.assertNotNull(certificate, "Certificate received");
+// Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509);
+// } catch (KeystoreException e) {
+// Assert.fail("Error occurred while generating certificate from CSR ", e);
+// }
+// }
+
+// @Test
+// public void testGetSignerKey() {
+// try {
+// PrivateKey privateKey = certificateGenerator.getSignerKey(CA_PRIVATE_KEY_PATH);
+//
+// Assert.assertNotNull(privateKey, "Private key received");
+// Assert.assertEquals(privateKey.getAlgorithm(), ConfigurationUtil.RSA);
+// } catch (KeystoreException e) {
+// Assert.fail("Error occurred while generating certificate ", e);
+// }
+// }
+//
+// @Test
+// public void testGetSigner() {
+// try {
+// X509Certificate certificate = certificateGenerator.getSigner(CA_CERT_PEM);
+//
+// Assert.assertNotNull(certificate, "Certificate received");
+// Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509);
+// } catch (KeystoreException e) {
+// Assert.fail("Error while retrieving certificate ", e);
+// }
+// }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtilTestSuite.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtilTestSuite.java
new file mode 100644
index 0000000000..45ab597868
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtilTestSuite.java
@@ -0,0 +1,38 @@
+package org.wso2.carbon.certificate.mgt.core.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import java.util.Date;
+
+public class CommonUtilTestSuite {
+
+ private static Log log = LogFactory.getLog(CommonUtilTestSuite.class);
+ private final CommonUtil commonUtil = new CommonUtil();
+
+ @Test
+ public void testValidityStartDate() {
+ Date validityStartDate = commonUtil.getValidityStartDate();
+
+ if(validityStartDate == null) {
+ Assert.fail("Validity start date is empty");
+ }
+
+ Date todayDate = new Date();
+ Assert.assertTrue(validityStartDate.before(todayDate), "Validity start date is valid");
+ }
+
+ @Test
+ public void testValidityEndDate() {
+ Date validityEndDate = commonUtil.getValidityEndDate();
+
+ if(validityEndDate == null) {
+ Assert.fail("Validity end date is empty");
+ }
+
+ Date todayDate = new Date();
+ Assert.assertTrue(validityEndDate.after(todayDate), "Validity end date is valid");
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.pem b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.pem
new file mode 100644
index 0000000000..417394bb96
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.pem
@@ -0,0 +1,34 @@
+-----BEGIN CERTIFICATE-----
+MIIF+zCCA+OgAwIBAgIJAJE458QXNuiLMA0GCSqGSIb3DQEBBQUAMIGLMQswCQYD
+VQQGEwJVUzENMAsGA1UECBMEVGVzdDENMAsGA1UEBxMEVGVzdDERMA8GA1UEChMI
+VGVzdCBPcmcxFjAUBgNVBAsTDVRlc3Qgb3JnIHVuaXQxFTATBgNVBAMTDFdTTzIg
+Um9vdCBDQTEcMBoGCSqGSIb3DQEJARYNcm9vdEB3c28yLmNvbTAeFw0xNTAxMjcx
+MjUxMjRaFw0xNzEwMjMxMjUxMjRaMIGLMQswCQYDVQQGEwJVUzENMAsGA1UECBME
+VGVzdDENMAsGA1UEBxMEVGVzdDERMA8GA1UEChMIVGVzdCBPcmcxFjAUBgNVBAsT
+DVRlc3Qgb3JnIHVuaXQxFTATBgNVBAMTDFdTTzIgUm9vdCBDQTEcMBoGCSqGSIb3
+DQEJARYNcm9vdEB3c28yLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC
+ggIBANJ756zjlkNKJf9O80qwFWxlwr4vOa80oaGXaO8Luj8ZNb7zyGATppTmZi2b
+rRVfNPGHhN/0REb5+Gcf0xvk1b5Wp4E+JoDKfZMwOVQsMVmKYHqopgiiE28L/YoN
+d0XmZA0J03nfQ4rzYggwQX7oRsW/AptkdURV4i8xD3SsqDGDZyYxQVDkj55nrweE
+d5FWOnYvvpdbFJ4WanJmGe1WRtLMJ0jFi7tw9Wc7W/5+fvIA9bvHDHoG1VlfyjQU
+SvTLlAN7Ui0ztXTcOZuN3HI0putMQRyaAD7Ljl7E1ROiqMhN/z80Bck8Yi7ELOmq
++cJOir/4CAamj8SugZ0iXo922slrSemWL9tjNT7MFmjFXmgIfVmaJF7OxKyxHhO8
+gJKTlU2KSJJH2CzMwnGdRFrDlsAotVjGLYFWHUN4HW2uA2crEEmk+UduwnVMazqU
+wBFxv+INf0U55bsXTv7C3L06IUaTBvxhxKQmzj9BeQGwWAC2Co4s5riT2ttivSRl
+XijPIEDTfmvE/fjj4KfQQOTY3+EejacMe6gb/qVsCZ1g9Tbk7WLgjYHBuOQSAz3l
+wPPqPY+6CakeL29wWyPg7pGzR6lMcYItUdHJuNsTijs0x6Xi1O5iIuL2o0vl8FRH
++tZFm3ujtCIHprjUgcn6aOR9Ms/NkUJCziKKAb4KoohNFgr/AgMBAAGjYDBeMB0G
+A1UdDgQWBBSDhLDYVCYhJsxvK1ZNV05qGGVajjAfBgNVHSMEGDAWgBSDhLDYVCYh
+JsxvK1ZNV05qGGVajjAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBhjANBgkq
+hkiG9w0BAQUFAAOCAgEAykqOsxHV43Bx24+7DfxLNYyafBayHacQ4uwtldwexyQB
+fIyJKjhzZUSvl37zhFPhJRJHogFIds+FoqaQsF8PvI/YSKs3UYRhje2mJan79lEA
+rCd+3zDGmzQhmutVo7C1bCQuujV8YLIJGvvcnMcHnMLpc5CfjzmI2C6qMZ5XgpHx
+/Mhindllqr0ZVvqRive0A2svW1k47XWB7BIfx/aoZ1viPHDNYVuYZ6j/NAFv8/Fu
+3n/TfYOJ5rz0NPGHYXnmFcgGxtYTu5u6Q9YVdDLZv9lqYbMRSdiQ8SVDzwxft9N5
+g6/VoXLoMpCS7/6jR3J0GbG2r/vr024QMOHDZHQDjkAVUBni6/bRHqj389RnOXhQ
++TSlx/hGgtdTpZRv63PjAqTCdDAhazWAgG/W+dxUhAywiOYHeXincuuDER0ypkfG
+caUvbN9/mWtGJvtW+L9OlTj3LQlXD2ORehz5itS3eV0DVkscCOLzzkVLtIJeew1o
+RmiADNOUe5A6V0cW5HIFi9F7Recqv9lGphwQeq+2cmvUKkSPcx+Z/SHTT/nIOioq
+xxafJhci5dAEsPgtzxnA6QqPQtxOj46aZxQh5+hzZ/1CQq3UThDdQreJL51c+NOS
+ZFQh6YVpJH6ZdSldBJnHjbS7RL/bv2kl1Pmv808T+iG+GpDw2XljwsI6TL8ACok=
+-----END CERTIFICATE-----
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_private.key b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_private.key
new file mode 100644
index 0000000000..d216007d3c
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_private.key
@@ -0,0 +1,51 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIJKgIBAAKCAgEA0nvnrOOWQ0ol/07zSrAVbGXCvi85rzShoZdo7wu6Pxk1vvPI
+YBOmlOZmLZutFV808YeE3/RERvn4Zx/TG+TVvlangT4mgMp9kzA5VCwxWYpgeqim
+CKITbwv9ig13ReZkDQnTed9DivNiCDBBfuhGxb8Cm2R1RFXiLzEPdKyoMYNnJjFB
+UOSPnmevB4R3kVY6di++l1sUnhZqcmYZ7VZG0swnSMWLu3D1Zztb/n5+8gD1u8cM
+egbVWV/KNBRK9MuUA3tSLTO1dNw5m43ccjSm60xBHJoAPsuOXsTVE6KoyE3/PzQF
+yTxiLsQs6ar5wk6Kv/gIBqaPxK6BnSJej3bayWtJ6ZYv22M1PswWaMVeaAh9WZok
+Xs7ErLEeE7yAkpOVTYpIkkfYLMzCcZ1EWsOWwCi1WMYtgVYdQ3gdba4DZysQSaT5
+R27CdUxrOpTAEXG/4g1/RTnluxdO/sLcvTohRpMG/GHEpCbOP0F5AbBYALYKjizm
+uJPa22K9JGVeKM8gQNN+a8T9+OPgp9BA5Njf4R6Npwx7qBv+pWwJnWD1NuTtYuCN
+gcG45BIDPeXA8+o9j7oJqR4vb3BbI+DukbNHqUxxgi1R0cm42xOKOzTHpeLU7mIi
+4vajS+XwVEf61kWbe6O0IgemuNSByfpo5H0yz82RQkLOIooBvgqiiE0WCv8CAwEA
+AQKCAgBAyt+AOvawdAzKULVX0mhl29Vc0hDBvEPdCEzG+Sc18T64LzcJTENFJr9h
+XsCjCZG0n/DpN7ok1yH+LK/BsGmTk/0wLb+QecS6IGglXw058PzOBUhG9A1ja596
+dba3j7pQwSuWIoIaLd2Jg8FFnZ7blHbq+ruWc5GS0Vleox+LTlXcTeE7U4BaVLRu
+bfqYhKCubPgQg3sPRvsxh/iHNL3MegfFwPnIk3cXdhBVgP725BDA4v8WOTBHuNL3
+wR9px5kikT20qGw9MuWQ2tR3W3neiLSqZ0WYDvUeexzUVIf8UPY3sH3vemUG3GCu
+9XC4vZC8k091LKSo+MbxZfkR1JZ4R2CEMcFJaz/jc6VN2bTOWuWWczReOzq0Xx7P
+GbsmcQNBhY8qBoz+cOWifxBWZzKSWfcNMgwnNyAKlDrOehpp+gZ1yH7dk9fL/wrE
+jSEEnhq4SVDeGEOo7gEi17Px8/256PKwQB4wELPBwODBslPzJ0PPDKk4mxBq3JQP
+EJKnBhu15KGJuoUZ42GcYSn55Zu/Rujqhn9cWbwhq0KrExwVI3EWnd89dYv360Mu
+RskqPTuEpAUOUCQPIUT0p3f1PBgML6L5HxjJDUt6n2N8Y1xT8sKF6FKnbvdizcqz
+v0+xdBk0xpSoazHzH1lnia3fZ6EPzMPHbLrz4ga0eUdaGwbSEQKCAQEA6sUljKKH
+7EsKsXaQ6igqQ2TkZWTu+xqRlFjb2tTmyHt99O4w3L45ae0la7ApygTRFHs3z9XB
+ws12bVkXdA35txKk97SNmWDrZbxpswHmTSnrOLGD2VFD4J/YifuBkT8K7PEJno9U
+Ewi70RHGQEFfL3VL1TOa2WnJELOLkzoCkBL/NaVawtbK7O7KIrCu3jFCq3zu+uku
+XVHTzXi+gr+uknGraxKcyLhCu6/7Uot+uYrtCzFsk4vTs2bovWuL2KLi/MAP8x3K
+FcNNj2SPr+PzwzlqthiW/rtZjg7MFMdN9RAhImjbIJt3svzWsB4nr7VQxHYStfFJ
+xIwbFp233qFKjQKCAQEA5YSK9L9o4LRDilwCz3p1tZ1tgY9tMUbG2wx0dG9xrETY
+4yGwTPAc++Tp3aOnbO544ZpnGLBoQTgtOc1p4jyj/Md2CwlP8UfbYhEdYEN9Gn5H
+ylu1b0cRwHeO4Bfnekqk8EL0rl3KUUsAk2uKEwCBwsuxjFurMDasyoA5T5gcsa4p
+EhEF5D7t5sJb7f8hP+vMBa2yUKQT9dflF8xN7iHvxhun1qipX1AzZ341H94QbgRb
+rYdfxzBr4aa5UZe5Ls9ofQf0S3zXVEXah/Pg+3o0BppdIrtLXTWcI/yeE6L8/Ebr
+jMXLiTzd4bwWjbTijEJ/MKb/UsPQqbZsXNzMiyxuuwKCAQEAvs0xQkYJr+ohK6+Q
+AS5ZguJpmVpZu6yRKn65V/V2BvQOn1RCU/Up1kQNCKNooy4c+sdVyc0RJ5AyspYY
+sJJ3I+m8NzD/b+tMBSgGw5xEnuv1puLmpGUehF2E8Ed+uxwAdidDySD1lG6hrj4C
+4NAAWyK6WfER5abK6Y7yXdpkoNE/p0rXI8jLrZo4n872n9BrPdJQq419yAwr1i9O
+rha4+330chXzZFIUslNJL4H9oTAejN1DP/sBOCnn96KDSrK/RemWTOEmD1/mFicF
+fE8IGt78Mjhz510+YGz4Qd7lJclRFJUhmjOgKdDBbutjF7OFi9XmSQZsDJhNn6jY
++dAeNQKCAQEAsAFpUfCq644xMRwIJ7VAKQrVnAIx+RTOj9JIR7XilPmi3OLLwORt
+RZmw4f+K99UUK+Vs5Bj7ifAbdnUYmp5oHwOSeTol7OBu0xBO17BJcpSeVwbm5rO4
+YEEO9rg+EaDGRV0DJ+fSq255vZM9Kf88gvYTbJArgeibrxqPWINMldD5u9oEC5la
+dJhdSPBaPhuDtGMUGBULHX73Nr28kT3DEsfIeKuUXvwwv0+gS5TOQp/i8fqbLzPp
+tvxUpsZUAxqYhTEhXPYaZoy+3Xze7dozpVCg1W6Nh6gB2fLyAhr+KDP2lFhmEhL0
+EBRds0Oga3De+p9FsuFo1YyIItpLnPpw2wKCAQEArUQM9k0Qprczx9sKf/YF+ulx
+tiiGyRUV7kAcrQiQAjB88wPoB/ovnW4VCI4y/mNeZGvyCWeQx9g+Ntc5BJlIlJYi
+wviyQ5Lq1OlOWQlWIkKCI2Z+s5uYKTSgZRp7VLnvKswHnxBy2Bxq3i9taP6QYlZz
+3ff/plfK3ZM6moc89wl/aQgdhWsV/WV7bKcnncM9K2N7dpKzRcZ+6iuJt9PNKo5V
+6GUYEvn04twumzgqGtYQbiq63YfHe8QLvX/j8ffGH8O0rUAIrQnrNl0n0SoE9ECU
+lUCVCXzypT+MKAeHfI4aFeWG48sdfnHPWOkyRHXWFLAwkHUVnqmYhXLpmJBtMw==
+-----END RSA PRIVATE KEY-----
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
new file mode 100755
index 0000000000..e19786b861
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
@@ -0,0 +1,19 @@
+
+
+
+
+ ${carbon.home}/repository/resources/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/log4j.properties b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/log4j.properties
new file mode 100644
index 0000000000..2143753b40
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/log4j.properties
@@ -0,0 +1,33 @@
+#
+# 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/ra_cert.pem b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ra_cert.pem
new file mode 100644
index 0000000000..516b08ccee
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ra_cert.pem
@@ -0,0 +1,33 @@
+-----BEGIN CERTIFICATE-----
+MIIFqDCCA5CgAwIBAgIBAjANBgkqhkiG9w0BAQUFADCBizELMAkGA1UEBhMCVVMx
+DTALBgNVBAgTBFRlc3QxDTALBgNVBAcTBFRlc3QxETAPBgNVBAoTCFRlc3QgT3Jn
+MRYwFAYDVQQLEw1UZXN0IG9yZyB1bml0MRUwEwYDVQQDEwxXU08yIFJvb3QgQ0Ex
+HDAaBgkqhkiG9w0BCQEWDXJvb3RAd3NvMi5jb20wHhcNMTUwMTI3MTI1MzAxWhcN
+MTcxMDIzMTI1MzAxWjCBgzELMAkGA1UEBhMCVVMxGTAXBgNVBAgTEFRlc3QgUkEg
+UHJvdmluY2UxFTATBgNVBAcTDFRlc3QgUkEgQ2l0eTEUMBIGA1UEChMLVGVzdCBS
+QSBPcmcxGTAXBgNVBAsTEFRlc3QgUkEgb3JnIHVuaXQxETAPBgNVBAMTCFdTTzIg
+UkEgMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtUMgUlYYU3/TPfEe
+zNAvBaiOi/jUjfZ9IbxvMl7obDT17/5vU68TCGkZRjyfYUEiGNBisUEFWjSk/sGL
+/ofYKUAxw33cd456FLMjaJX/4Zk4y8eYB1m1GGlHejoDyjPhq8S6GDmy+PXbJr8n
+lSTROR2mQHkGwYrCreWeU4AYWzdctIFk7U2DKeIvZYSidIIjfSpDXURxrt9LPvig
+fMzr5l/WkZfjvk5S+W7rgMtpllxlEPgyDc07pNAdNSq5FB990oaUsVX8o6l6wdCw
+grYz83edPOKwZa04fsVztz2oF3ZYSGGjD3lwh0KS/jUL+awRyhMx5p/O1hySg6PP
+pJjeqRuobNTuwSAXxp3nsNSY0DkGW04pSxWoDQqhnpaqBbAf71l6ya2e3so1SHm/
+jouWSYTHncq5bmGE4AN7ZGVGZvfx84+UR8fNxJxxLo+DFFE0oJNzpPGNxILpHxgT
+V7IOII6mhfkrQk+AFQiW2Y5FXLVYv8r+SPXW8pYsjaWl971XZeM/HC3L9IZkCrrr
+a0ID5oT6vt+xTmdo4yiBqIP5TBYm+1a9YzMAy7XGtPih9k6cufMLcfzvUZdOXw9x
+3T05nM5ZtcDq0gHvUzQ7sfHTguWVnuHVEdb2ox4x2L5NzEA475fbSdXpMok9z/z7
+Xa71vIZi28InDAFBQehUlJnFtf0CAwEAAaMdMBswDAYDVR0TBAUwAwEB/zALBgNV
+HQ8EBAMCBaAwDQYJKoZIhvcNAQEFBQADggIBAAO0TwnQBMJvL8wbfsnTqAGCCHM4
+x1cpW+KgTmflPEliYGOn/dJYDz/dUowCgoj5mrSxjQ3G1/qL+9Y7E33h0tyw37vH
+YDL1p2Tn+fwmXRHrk+CHoPHNcImEfSIDWbbG7ehBR6erVfbQSZjmj4fwPkItp8rP
+nyUtXHOLpfFYoAxYkNP9+C8vpC9W/H1pj3rzmQFA1z+EZAKVV7vDAxbe6sun84nf
+YAaMSIzHx1B+XLHokgChmnZr3wV7EypBEmmKp4ITvJqK7WsIG9t1M6hI7OTPCURR
+mdy+DJtIoIUbZxHyIyC9nPcVJFkdBusnfXq4uMb0KMaWYCU8ESqZPySukF2qZ5KA
+acB+0ZhY+EGQ6QF/hB6iiUj96BlQ7XAPXFU6xUt6nRjDiJmb3vW1IEv0hpbs7PRl
+UMlbOwQk37rXpFqQc6ZW7lsxI2RmfkD4DOkQIGH3q5foVr+PEp0uSPWrFX62eBet
+1S4c/opVv6BcuUgilYABHTYxb45GfYwJAI9Qw2uQWT8DmhtVbcYu6GLYGlnRyaOC
+EPzc0z0KQTjhsgHWzi60IYBBh+fy+Z7w5X1rTTvhFOoU5J7kedGEqiBatIZmhF5t
+UFbT0u350ET5a0Kg83gu5aLwXdoIP9o7bp3XzLBMVNny2RX3tOHUA2HBe/p0h0OU
+Ggt3G6oD0gBe9pZI
+-----END CERTIFICATE-----
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
new file mode 100644
index 0000000000..8d91ced59f
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/wso2certs.jks b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/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/wso2certs.jks differ
diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml
new file mode 100644
index 0000000000..7316cac2e4
--- /dev/null
+++ b/components/certificate-mgt/pom.xml
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+ org.wso2.carbon.devicemgt
+ carbon-devicemgt
+ 0.9.2-SNAPSHOT
+ ../../pom.xml
+
+
+ 4.0.0
+ org.wso2.carbon.devicemgt
+ certificate-mgt
+ 0.9.2-SNAPSHOT
+ pom
+ WSO2 Carbon - Certificate Management Component
+ http://wso2.org
+
+
+ org.wso2.carbon.certificate.mgt.core
+
+
+
+
+
+
+ org.apache.felix
+ maven-scr-plugin
+ 1.7.2
+
+
+ generate-scr-scrdescriptor
+
+ scr
+
+
+
+
+
+
+
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java
index 331c81b749..07842fbc6b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java
@@ -19,9 +19,12 @@ package org.wso2.carbon.device.mgt.common;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
+import java.io.Serializable;
import java.util.List;
-public class Device {
+public class Device implements Serializable{
+
+ private static final long serialVersionUID = 1998101711L;
private int id;
private String name;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java
index 2c599474fc..d6c399d130 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java
@@ -18,7 +18,11 @@
*/
package org.wso2.carbon.device.mgt.common;
-public class EnrolmentInfo {
+import java.io.Serializable;
+
+public class EnrolmentInfo implements Serializable{
+
+ private static final long serialVersionUID = 1998101712L;
public enum Status {
CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED
@@ -28,6 +32,7 @@ public class EnrolmentInfo {
BYOD, COPE
}
+ private int id;
private Device device;
private Long dateOfEnrolment;
private Long dateOfLastUpdate;
@@ -44,6 +49,14 @@ public class EnrolmentInfo {
this.status = status;
}
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
public Long getDateOfEnrolment() {
return dateOfEnrolment;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java
new file mode 100644
index 0000000000..049d7e166c
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/IllegalTransactionStateException.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.wso2.carbon.device.mgt.common;
+
+public class IllegalTransactionStateException extends RuntimeException {
+
+ private static final long serialVersionUID = -3151279331929070297L;
+
+ private String errorMessage;
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public IllegalTransactionStateException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
+
+ public IllegalTransactionStateException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
+
+ public IllegalTransactionStateException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
+
+ public IllegalTransactionStateException() {
+ super();
+ }
+
+ public IllegalTransactionStateException(Throwable cause) {
+ super(cause);
+ }
+
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java
new file mode 100644
index 0000000000..370f37fe29
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java
@@ -0,0 +1,55 @@
+/*
+ * 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.device.mgt.common.configuration.mgt;
+
+public class ConfigurationManagementException extends Exception {
+ private static final long serialVersionUID = -3151279311929070299L;
+
+ private String errorMessage;
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public ConfigurationManagementException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
+
+ public ConfigurationManagementException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
+
+ public ConfigurationManagementException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
+
+ public ConfigurationManagementException() {
+ super();
+ }
+
+ public ConfigurationManagementException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java
new file mode 100644
index 0000000000..59b9e1c7ae
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java
@@ -0,0 +1,45 @@
+/*
+ * 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.device.mgt.common.configuration.mgt;
+
+/**
+ * This represents the tenant configuration management functionality which should be implemented by
+ * the device type plugins.
+ */
+public interface TenantConfigurationManagementService {
+
+ /**
+ * Method to add a operation to a device or a set of devices.
+ *
+ * @param tenantConfiguration Operation to be added.
+ * @param resourcePath Registry resource path.
+ * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the
+ * configuration.
+ */
+ public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws ConfigurationManagementException;
+
+ /**
+ * Method to retrieve the list of general tenant configurations.
+ *
+ * @param resourcePath Registry resource path.
+ * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the
+ * operation list.
+ */
+ public TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException;
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java
index 78e81dbe1a..ea0ce55365 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java
@@ -45,6 +45,7 @@ import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
import java.rmi.RemoteException;
+import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@@ -173,6 +174,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
@Override
public void updateApplicationListInstalledInDevice(
DeviceIdentifier deviceIdentifier, List applications) throws ApplicationManagementException {
+ List installedAppList = getApplicationListForDevice(deviceIdentifier);
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManagementDAOFactory.beginTransaction();
@@ -182,8 +184,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId());
}
- List installedAppList = getApplicationListForDevice(deviceIdentifier);
-
if (log.isDebugEnabled()) {
log.debug("num of apps installed:" + installedAppList.size());
}
@@ -227,9 +227,13 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
}
applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId);
DeviceManagementDAOFactory.commitTransaction();
- } catch (DeviceManagementDAOException | TransactionManagementException e) {
+ } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new ApplicationManagementException("Error occurred saving application list to the device", e);
+ } catch (TransactionManagementException e) {
+ throw new ApplicationManagementException("Error occurred while initializing transaction", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
}
}
@@ -239,11 +243,16 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
Device device;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceId, tenantId);
return applicationDAO.getInstalledApplications(device.getId());
} catch (DeviceManagementDAOException e) {
- throw new ApplicationManagementException("Error occured while fetching the Application List of '" +
+ throw new ApplicationManagementException("Error occurred while fetching the Application List of '" +
deviceId.getType() + "' device carrying the identifier'" + deviceId.getId(), e);
+ } catch (SQLException e) {
+ throw new ApplicationManagementException("Error occurred while opening a connection to the data source", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java
new file mode 100644
index 0000000000..2006ac336e
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java
@@ -0,0 +1,41 @@
+/*
+ * 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.device.mgt.core.config;
+
+/**
+ * This class holds the constants used throughout the configuration manager.
+ */
+public class ConfigurationManagerConstants {
+
+ public static final class ContentTypes {
+ private ContentTypes() {
+ throw new AssertionError();
+ }
+
+ public static final String CONTENT_TYPE_ANY = "*/*";
+ public static final String MEDIA_TYPE_XML = "application/xml";
+ }
+
+ public static final class CharSets {
+ private CharSets() {
+ throw new AssertionError();
+ }
+
+ public static final String CHARSET_UTF8 = "UTF8";
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionManager.java
index 2681ebc8e0..0e370b3825 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionManager.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionManager.java
@@ -66,8 +66,11 @@ public class PermissionManager {
/* Un-marshaling Device Management configuration */
JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class);
Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
- PermissionConfiguration permissionConfiguration = (PermissionConfiguration) unmarshaller.unmarshal(permissionStream);
- this.addPermissions(permissionConfiguration.getPermissions());
+ PermissionConfiguration permissionConfiguration = (PermissionConfiguration)
+ unmarshaller.unmarshal(permissionStream);
+ if((permissionConfiguration != null) && (permissionConfiguration.getPermissions() != null)){
+ this.addPermissions(permissionConfiguration.getPermissions());
+ }
}
} catch (JAXBException e) {
throw new DeviceManagementException("Error occurred while initializing Data Source config", e);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java
index fe38dbbd95..deb10035bc 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java
@@ -24,34 +24,64 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "PolicyConfiguration")
public class PolicyConfiguration {
- private String monitoringClass;
- private int maxRetries;
- private int minRetriesToMarkUnreachable;
-
- @XmlElement(name = "monitoringClass", required = true)
- public String getMonitoringClass() {
- return monitoringClass;
- }
-
- public void setMonitoringClass(String monitoringClass) {
- this.monitoringClass = monitoringClass;
- }
-
- @XmlElement(name = "maxRetries", required = true)
- public int getMaxRetries() {
- return maxRetries;
- }
-
- public void setMaxRetries(int maxRetries) {
- this.maxRetries = maxRetries;
- }
-
- @XmlElement(name = "minRetriesToMarkUnreachable", required = true)
- public int getMinRetriesToMarkUnreachable() {
- return minRetriesToMarkUnreachable;
- }
-
- public void setMinRetriesToMarkUnreachable(int minRetriesToMarkUnreachable) {
- this.minRetriesToMarkUnreachable = minRetriesToMarkUnreachable;
- }
+ private String monitoringClass;
+ private boolean monitoringEnable;
+ private int monitoringFrequency;
+ private int maxRetries;
+ private int minRetriesToMarkUnreachable;
+ private int minRetriesToMarkInactive;
+
+ @XmlElement(name = "monitoringClass", required = true)
+ public String getMonitoringClass() {
+ return monitoringClass;
+ }
+
+ public void setMonitoringClass(String monitoringClass) {
+ this.monitoringClass = monitoringClass;
+ }
+
+ @XmlElement(name = "maxRetries", required = true)
+ public int getMaxRetries() {
+ return maxRetries;
+ }
+
+ public void setMaxRetries(int maxRetries) {
+ this.maxRetries = maxRetries;
+ }
+
+ @XmlElement(name = "minRetriesToMarkUnreachable", required = true)
+ public int getMinRetriesToMarkUnreachable() {
+ return minRetriesToMarkUnreachable;
+ }
+
+ public void setMinRetriesToMarkUnreachable(int minRetriesToMarkUnreachable) {
+ this.minRetriesToMarkUnreachable = minRetriesToMarkUnreachable;
+ }
+
+ @XmlElement(name = "monitoringEnable", required = true)
+ public boolean getMonitoringEnable() {
+ return monitoringEnable;
+ }
+
+ public void setMonitoringEnable(boolean monitoringEnable) {
+ this.monitoringEnable = monitoringEnable;
+ }
+
+ @XmlElement(name = "minRetriesToMarkInactive", required = true)
+ public int getMinRetriesToMarkInactive() {
+ return minRetriesToMarkInactive;
+ }
+
+ public void setMinRetriesToMarkInactive(int minRetriesToMarkInactive) {
+ this.minRetriesToMarkInactive = minRetriesToMarkInactive;
+ }
+
+ @XmlElement(name = "monitoringFrequency", required = true)
+ public int getMonitoringFrequency() {
+ return monitoringFrequency;
+ }
+
+ public void setMonitoringFrequency(int monitoringFrequency) {
+ this.monitoringFrequency = monitoringFrequency;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java
new file mode 100644
index 0000000000..803a53f7ff
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java
@@ -0,0 +1,97 @@
+/*
+ * 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.device.mgt.core.config.tenant;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
+import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
+import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
+import org.wso2.carbon.device.mgt.core.config.ConfigurationManagerConstants;
+import org.wso2.carbon.device.mgt.core.config.util.ConfigurationManagerUtil;
+import org.wso2.carbon.registry.api.Resource;
+import org.wso2.carbon.registry.api.RegistryException;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.nio.charset.Charset;
+
+/**
+ * This class implements all the functionality exposed as part of the TenantConfigurationManagementService. Main usage of
+ * this module is, saving/retrieving tenant configurations to the registry.
+ */
+public class TenantConfigurationManagementServiceImpl
+ implements TenantConfigurationManagementService {
+
+ private static final Log log = LogFactory.getLog(TenantConfigurationManagementServiceImpl.class);
+
+ @Override
+ public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath)
+ throws ConfigurationManagementException {
+ boolean status;
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Persisting tenant configurations in Registry");
+ }
+ StringWriter writer = new StringWriter();
+ JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.marshal(tenantConfiguration, writer);
+
+ Resource resource = ConfigurationManagerUtil.getConfigurationRegistry().newResource();
+ resource.setContent(writer.toString());
+ resource.setMediaType(ConfigurationManagerConstants.ContentTypes.MEDIA_TYPE_XML);
+ ConfigurationManagerUtil.putRegistryResource(resourcePath, resource);
+ status = true;
+ } catch (RegistryException e) {
+ throw new ConfigurationManagementException(
+ "Error occurred while persisting the Registry resource of Tenant Configuration : " + e.getMessage(), e);
+ } catch (JAXBException e) {
+ throw new ConfigurationManagementException(
+ "Error occurred while parsing the Tenant configuration : " + e.getMessage(), e);
+ }
+ return status;
+ }
+
+ @Override
+ public TenantConfiguration getConfiguration(String resourcePath)
+ throws ConfigurationManagementException {
+ Resource resource;
+ try {
+ resource = ConfigurationManagerUtil.getRegistryResource(resourcePath);
+ if(resource != null){
+ JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ return (TenantConfiguration) unmarshaller.unmarshal(
+ new StringReader(new String((byte[]) resource.getContent(), Charset
+ .forName(ConfigurationManagerConstants.CharSets.CHARSET_UTF8))));
+ }
+ return new TenantConfiguration();
+ } catch (JAXBException e) {
+ throw new ConfigurationManagementException(
+ "Error occurred while parsing the Tenant configuration : " + e.getMessage(), e);
+ } catch (RegistryException e) {
+ throw new ConfigurationManagementException(
+ "Error occurred while retrieving the Registry resource of Tenant Configuration : " + e.getMessage(), e);
+ }
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java
new file mode 100644
index 0000000000..58a54ef0f0
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java
@@ -0,0 +1,70 @@
+/*
+ * 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.device.mgt.core.config.util;
+
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
+import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
+import org.wso2.carbon.registry.api.RegistryException;
+import org.wso2.carbon.registry.api.Resource;
+import org.wso2.carbon.registry.core.Registry;
+
+public class ConfigurationManagerUtil {
+
+ public static Registry getConfigurationRegistry() throws ConfigurationManagementException {
+ try {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+ return DeviceManagementDataHolder.getInstance().getRegistryService()
+ .getConfigSystemRegistry(
+ tenantId);
+ } catch (RegistryException e) {
+ throw new ConfigurationManagementException(
+ "Error in retrieving governance registry instance: " +
+ e.getMessage(), e);
+ }
+ }
+
+ public static Resource getRegistryResource(String path) throws ConfigurationManagementException {
+ try {
+ if(ConfigurationManagerUtil.getConfigurationRegistry().resourceExists(path)){
+ return ConfigurationManagerUtil.getConfigurationRegistry().get(path);
+ }
+ return null;
+ } catch (RegistryException e) {
+ throw new ConfigurationManagementException("Error in retrieving registry resource : " +
+ e.getMessage(), e);
+ }
+ }
+
+ public static boolean putRegistryResource(String path,
+ Resource resource)
+ throws ConfigurationManagementException {
+ boolean status;
+ try {
+ ConfigurationManagerUtil.getConfigurationRegistry().beginTransaction();
+ ConfigurationManagerUtil.getConfigurationRegistry().put(path, resource);
+ ConfigurationManagerUtil.getConfigurationRegistry().commitTransaction();
+ status = true;
+ } catch (RegistryException e) {
+ throw new ConfigurationManagementException(
+ "Error occurred while persisting registry resource : " +
+ e.getMessage(), e);
+ }
+ return status;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java
index 8d28f17825..670935f3bb 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java
@@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
@@ -113,8 +114,14 @@ public class DeviceManagementDAOFactory {
}
public static void beginTransaction() throws TransactionManagementException {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ throw new IllegalTransactionStateException("A transaction is already active within the context of " +
+ "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
+ "transaction is already active is a sign of improper transaction handling");
+ }
try {
- Connection conn = dataSource.getConnection();
+ conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
@@ -123,58 +130,67 @@ public class DeviceManagementDAOFactory {
}
public static void openConnection() throws SQLException {
- currentConnection.set(dataSource.getConnection());
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ throw new IllegalTransactionStateException("A transaction is already active within the context of " +
+ "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
+ "transaction is already active is a sign of improper transaction handling");
+ }
+ conn = dataSource.getConnection();
+ currentConnection.set(conn);
}
public static Connection getConnection() throws SQLException {
- if (currentConnection.get() == null) {
- currentConnection.set(dataSource.getConnection());
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
}
- return currentConnection.get();
+ return conn;
}
public static void commitTransaction() {
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
try {
- Connection conn = currentConnection.get();
- if (conn != null) {
- conn.commit();
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Datasource connection associated with the current thread is null, hence commit " +
- "has not been attempted");
- }
- }
+ conn.commit();
} catch (SQLException e) {
log.error("Error occurred while committing the transaction", e);
}
}
public static void rollbackTransaction() {
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
try {
- Connection conn = currentConnection.get();
- if (conn != null) {
- conn.rollback();
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Datasource connection associated with the current thread is null, hence rollback " +
- "has not been attempted");
- }
- }
+ conn.rollback();
} catch (SQLException e) {
- log.warn("Error occurred while rollbacking the transaction", e);
+ log.warn("Error occurred while roll-backing the transaction", e);
}
}
public static void closeConnection() {
- Connection con = currentConnection.get();
- if (con != null) {
- try {
- con.close();
- } catch (SQLException e) {
- log.warn("Error occurred while close the connection");
- }
- currentConnection.remove();
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while close the connection");
}
+ currentConnection.remove();
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java
index 6978854e6b..1384d677d4 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java
@@ -26,7 +26,7 @@ public interface EnrolmentDAO {
int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;
int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
- int tenantId) throws DeviceManagementDAOException;
+ int tenantId) throws DeviceManagementDAOException;
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java
index 981db85305..8e56611751 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java
@@ -111,16 +111,16 @@ public class ApplicationMappingDAOImpl implements ApplicationMappingDAO {
"APPLICATION_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
- for(Integer appId:appIdList){
+ for (Integer appId : appIdList) {
stmt.setInt(1, deviceId);
stmt.setInt(2, appId);
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
- } catch (SQLException e) {
+ } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while adding device application mapping", e);
- }finally {
+ } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java
index 35e8466712..814084aa70 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java
@@ -111,7 +111,7 @@ public class DeviceDAOImpl implements DeviceDAO {
conn = this.getConnection();
String sql =
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " +
- "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT " +
+ "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " +
"t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
@@ -177,7 +177,7 @@ public class DeviceDAOImpl implements DeviceDAO {
String sql =
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " +
- "FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME " +
+ "FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " +
"AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
@@ -208,7 +208,7 @@ public class DeviceDAOImpl implements DeviceDAO {
String sql =
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
- "e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT t.NAME AS DEVICE_TYPE, d.ID, d.DESCRIPTION, " +
+ "e.DATE_OF_ENROLMENT , e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT t.NAME AS DEVICE_TYPE, d.ID, d.DESCRIPTION, " +
"d.NAME, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?";
@@ -473,6 +473,7 @@ public class DeviceDAOImpl implements DeviceDAO {
private EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
+ enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
@@ -491,7 +492,7 @@ public class DeviceDAOImpl implements DeviceDAO {
String sql =
"SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
- "e.DATE_OF_ENROLMENT FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " +
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE FROM DM_ENROLMENT e WHERE TENANT_ID = ? " +
"AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
@@ -513,4 +514,5 @@ public class DeviceDAOImpl implements DeviceDAO {
}
return devices;
}
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
index 6acdd01d5b..4e54268916 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
@@ -24,6 +24,7 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
+import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
@@ -36,6 +37,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfiguration
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
+import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
@@ -171,6 +173,11 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider);
bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null);
+ /* Registering Tenant Configuration Management Service */
+ TenantConfigurationManagementService
+ tenantConfiguration = new TenantConfigurationManagementServiceImpl();
+ bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null);
+
/* Registering App Management service */
try {
AppManagementConfigurationManager.getInstance().initConfig();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
index b2e593291d..0315ded100 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
@@ -76,11 +76,12 @@ public class OperationManagerImpl implements OperationManager {
log.debug("operation:[" + operation.toString() + "]");
for (DeviceIdentifier deviceIdentifier : deviceIds) {
log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" +
- deviceIdentifier.getType() + "]");
+ deviceIdentifier.getType() + "]");
}
}
try {
OperationManagementDAOFactory.beginTransaction();
+
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
OperationDAOUtil.convertOperation(operation);
@@ -89,7 +90,16 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
for (DeviceIdentifier deviceId : deviceIds) {
- enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } catch (SQLException e) {
+ throw new OperationManagementException("Error occurred while opening a connection the data " +
+ "source", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
+
if (enrolmentId < 0) {
String errorMsg = "The operation not added for device.The device not found for " +
"device Identifier type -'" + deviceId.getType() + "' and device Id '" +
@@ -119,10 +129,15 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId;
List operations = new ArrayList<>();
try {
- OperationManagementDAOFactory.openConnection();
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device " +
@@ -160,14 +175,20 @@ public class OperationManagerImpl implements OperationManager {
List operations = new ArrayList<>();
List dtoOperationList = new ArrayList<>();
try {
- OperationManagementDAOFactory.openConnection();
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
+
+ OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for the given device Identifier:" +
- deviceId.getId() + " and given type:" + deviceId.getType());
+ deviceId.getId() + " and given type:" + deviceId.getType());
}
dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(
@@ -213,10 +234,15 @@ public class OperationManagerImpl implements OperationManager {
Operation operation = null;
int enrolmentId;
try {
- OperationManagementDAOFactory.openConnection();
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device " +
@@ -264,11 +290,19 @@ public class OperationManagerImpl implements OperationManager {
if (log.isDebugEnabled()) {
log.debug("operation Id:" + operationId + " status:" + operation.getStatus());
}
+ int enrolmentId;
try {
- OperationManagementDAOFactory.beginTransaction();
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } catch (SQLException e) {
+ throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- int enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ OperationManagementDAOFactory.beginTransaction();
if (operation.getStatus() != null) {
operationDAO.updateOperationStatus(enrolmentId, operationId,
@@ -327,10 +361,16 @@ public class OperationManagerImpl implements OperationManager {
deviceId.getId());
}
try {
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
+
OperationManagementDAOFactory.openConnection();
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device identifier:" +
deviceId.getId() + " type:" + deviceId.getType());
@@ -383,12 +423,17 @@ public class OperationManagerImpl implements OperationManager {
List operations = new ArrayList<>();
List dtoOperationList =
new ArrayList<>();
+ int enrolmentId;
try {
+ try {
+ DeviceManagementDAOFactory.openConnection();
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
+ }
OperationManagementDAOFactory.openConnection();
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- int enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
-
if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for device id:" + deviceId.getId() + " " +
"type:" + deviceId.getType());
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java
index 6ed2e443ad..e43843a474 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java
@@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
@@ -87,7 +88,9 @@ public class OperationManagementDAOFactory {
public static Connection getConnection() throws SQLException {
if (currentConnection.get() == null) {
- currentConnection.set(dataSource.getConnection());
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
}
return currentConnection.get();
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
index 172fa38633..4d9516e795 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
@@ -157,9 +157,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
device.getDeviceIdentifier() + "', which belongs to " + "platform '" +
device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'");
}
- } catch (TransactionManagementException | DeviceManagementDAOException e) {
+ } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
- log.error("Error occurred while adding enrolment related metadata", e);
+ throw new DeviceManagementException("Error occurred while adding enrolment related metadata", e);
+ } catch (TransactionManagementException e) {
+ throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -174,10 +176,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId);
enrolmentId = enrolmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction();
- } catch (DeviceManagementDAOException | TransactionManagementException e) {
+ } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
- log.error("Error occurred while adding metadata of '" + device.getType() + "' device carrying " +
- "the identifier '" + device.getDeviceIdentifier() + "'", e);
+ throw new DeviceManagementException("Error occurred while adding metadata of '" + device.getType() +
+ "' device carrying the identifier '" + device.getDeviceIdentifier() + "'", e);
+ } catch (TransactionManagementException e) {
+ throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -215,10 +219,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
enrolmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction();
- } catch (DeviceManagementDAOException | TransactionManagementException e) {
+ } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while modifying the device " +
"'" + device.getId() + "'", e);
+ } catch (TransactionManagementException e) {
+ throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -248,10 +254,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceDAO.updateDevice(deviceType.getId(), device, tenantId);
DeviceManagementDAOFactory.commitTransaction();
- } catch (DeviceManagementDAOException | TransactionManagementException e) {
+ } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while dis-enrolling '" + deviceId.getType() +
"' device with the identifier '" + deviceId.getId() + "'", e);
+ } catch (TransactionManagementException e) {
+ throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -303,14 +311,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
List allDevices;
try {
DeviceManagementDAOFactory.openConnection();
-
allDevices = deviceDAO.getDevices(this.getTenantId());
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " +
"the current tenant", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
+
for (Device device : allDevices) {
DeviceManager deviceManager = this.getDeviceManager(device.getType());
if (deviceManager == null) {
@@ -339,9 +349,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try {
DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevices(deviceType, this.getTenantId());
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving all devices of type '" +
deviceType + "' that are being managed within the scope of current tenant", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -416,7 +428,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
.getProperty("line.separator")).append(messageFooter3.trim());
} catch (IOException e) {
- log.error("IO error in processing enrol email message " + emailMessageProperties);
throw new DeviceManagementException("Error replacing tags in email template '" +
emailMessageProperties.getSubject() + "'", e);
}
@@ -480,7 +491,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
messageBuilder.append(System.getProperty("line.separator")).append(messageFooter3.trim());
} catch (IOException e) {
- log.error("IO error in processing enrol email message " + emailMessageProperties);
throw new DeviceManagementException("Error replacing tags in email template '" +
emailMessageProperties.getSubject() + "'", e);
}
@@ -493,10 +503,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
+ DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceId, this.getTenantId());
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while obtaining the device for id " +
"'" + deviceId.getId() + "'", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -571,9 +584,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.commitTransaction();
return success;
- } catch (DeviceManagementDAOException | TransactionManagementException e) {
+ } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while setting enrollment status", e);
+ } catch (TransactionManagementException e) {
+ throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -620,8 +635,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
@Override
- public int addOperation(Operation operation, List devices) throws
- OperationManagementException {
+ public int addOperation(Operation operation,
+ List devices) throws OperationManagementException {
return DeviceManagementDataHolder.getInstance().getOperationManager().addOperation(operation, devices);
}
@@ -652,8 +667,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
@Override
- public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
- throws OperationManagementException {
+ public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId,
+ int operationId) throws OperationManagementException {
return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByDeviceAndOperationId(
deviceId, operationId);
}
@@ -678,9 +693,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try {
DeviceManagementDAOFactory.openConnection();
userDevices = deviceDAO.getDevicesOfUser(username, this.getTenantId());
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the list of devices that " +
"belong to the user '" + username + "'", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -751,8 +768,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try {
DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDeviceCount(this.getTenantId());
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the device count", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -765,9 +784,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try {
DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesByName(deviceName, this.getTenantId());
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '"
+ deviceName + "'", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -789,14 +810,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override
public void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status status) throws DeviceManagementException {
try {
+ DeviceManagementDAOFactory.beginTransaction();
+
DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType());
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.getEnrolmentInfo().setStatus(status);
deviceDAO.updateDevice(deviceType.getId(), device, this.getTenantId());
- } catch (DeviceManagementDAOException deviceDaoEx) {
- String errorMsg = "Error occured update device enrolment status : " + device.getId();
- log.error(errorMsg, deviceDaoEx);
- throw new DeviceManagementException(errorMsg, deviceDaoEx);
+
+ DeviceManagementDAOFactory.commitTransaction();
+ } catch (DeviceManagementDAOException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
+ throw new DeviceManagementException("Error occurred update device enrolment status : '" +
+ device.getId() + "'", e);
+ } catch (TransactionManagementException e) {
+ throw new DeviceManagementException("Error occurred while initiating transaction", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
}
}
@@ -827,12 +856,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try {
DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesByStatus(status, this.getTenantId());
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException(
"Error occurred while fetching the list of devices that matches to status: '" + status + "'", e);
+ } catch (SQLException e) {
+ throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
-
}
for (Device device : allDevices) {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
index ac64d714a2..bf2ee59a39 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
@@ -23,6 +23,7 @@ import org.w3c.dom.Document;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
@@ -35,6 +36,7 @@ import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
+import java.sql.SQLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
@@ -97,6 +99,7 @@ public final class DeviceManagerUtil {
public static boolean registerDeviceType(String typeName) throws DeviceManagementException {
boolean status;
try {
+ DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName);
if (deviceType == null) {
@@ -104,10 +107,18 @@ public final class DeviceManagerUtil {
dt.setName(typeName);
deviceTypeDAO.addDeviceType(dt);
}
+ DeviceManagementDAOFactory.commitTransaction();
status = true;
} catch (DeviceManagementDAOException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '" +
typeName + "'", e);
+ } catch (TransactionManagementException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
+ throw new DeviceManagementException("SQL occurred while registering the device type '" +
+ typeName + "'", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
}
return status;
}
@@ -120,6 +131,7 @@ public final class DeviceManagerUtil {
*/
public static boolean unregisterDeviceType(String typeName) throws DeviceManagementException {
try {
+ DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName);
if (deviceType != null) {
@@ -127,10 +139,18 @@ public final class DeviceManagerUtil {
dt.setName(typeName);
deviceTypeDAO.removeDeviceType(typeName);
}
+ DeviceManagementDAOFactory.commitTransaction();
return true;
} catch (DeviceManagementDAOException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '" +
typeName + "'", e);
+ } catch (TransactionManagementException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
+ throw new DeviceManagementException("SQL occurred while registering the device type '" +
+ typeName + "'", e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java
index edab3737a2..c5b69b3a17 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java
@@ -42,7 +42,8 @@ public class ApplicationManagementProviderServiceTest {
@BeforeClass
public void init() {
deviceManagementPluginRepository = new DeviceManagementPluginRepository();
- TestDeviceManagementService testDeviceManagementService = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
+ TestDeviceManagementService testDeviceManagementService =
+ new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
try {
deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService);
} catch (DeviceManagementException e) {
@@ -53,11 +54,11 @@ public class ApplicationManagementProviderServiceTest {
}
@Test
- public void updateApplicationTest(){
+ public void updateApplicationTest() {
- List applications = new ArrayList();
+ List applications = new ArrayList<>();
- Application application1 = TestDataHolder.generateApplicationDummyData("org.wso2.app1");
+ Application application1 = TestDataHolder.generateApplicationDummyData("org.wso2.app1");
Application application2 = TestDataHolder.generateApplicationDummyData("org.wso2.app2");
Application application3 = TestDataHolder.generateApplicationDummyData("org.wso2.app3");
Application application4 = TestDataHolder.generateApplicationDummyData("org.wso2.app4");
@@ -67,34 +68,43 @@ public class ApplicationManagementProviderServiceTest {
applications.add(application3);
applications.add(application4);
- Device device = TestDataHolder.initialTestDevice;
- DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
- deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier);
- deviceIdentifier.setType(device.getType());
+ Device device = TestDataHolder.initialTestDevice;
+
+ if (device == null) {
+ throw new IllegalStateException("Device information is not available");
+ }
+ DeviceIdentifier deviceId = new DeviceIdentifier();
+
+ String deviceIdentifier = TestDataHolder.initialDeviceIdentifier;
+ if (deviceIdentifier == null) {
+ throw new IllegalStateException("Device identifier is not available");
+ }
+ deviceId.setId(deviceIdentifier);
+ deviceId.setType(device.getType());
AppManagementConfig appManagementConfig = new AppManagementConfig();
appMgtProvider = new ApplicationManagerProviderServiceImpl(deviceManagementPluginRepository);
try {
- appMgtProvider.updateApplicationListInstalledInDevice(deviceIdentifier, applications);
- } catch (ApplicationManagementException appMgtEx){
+ appMgtProvider.updateApplicationListInstalledInDevice(deviceId, applications);
+ } catch (ApplicationManagementException appMgtEx) {
String msg = "Error occurred while updating app list '" + TestDataHolder.TEST_DEVICE_TYPE + "'";
log.error(msg, appMgtEx);
Assert.fail(msg, appMgtEx);
}
Application application5 = TestDataHolder.generateApplicationDummyData("org.wso2.app5");
- applications = new ArrayList();
+ applications = new ArrayList<>();
applications.add(application4);
applications.add(application3);
applications.add(application5);
try {
- appMgtProvider.updateApplicationListInstalledInDevice(deviceIdentifier, applications);
- List installedApps = appMgtProvider.getApplicationListForDevice(deviceIdentifier);
- log.info("Number of installed applications:"+installedApps.size());
- Assert.assertEquals(installedApps.size(),3,"Num of installed applications should be two");
- } catch (ApplicationManagementException appMgtEx){
+ appMgtProvider.updateApplicationListInstalledInDevice(deviceId, applications);
+ List installedApps = appMgtProvider.getApplicationListForDevice(deviceId);
+ log.info("Number of installed applications:" + installedApps.size());
+ Assert.assertEquals(installedApps.size(), 3, "Num of installed applications should be two");
+ } catch (ApplicationManagementException appMgtEx) {
String msg = "Error occurred while updating app list '" + TestDataHolder.TEST_DEVICE_TYPE + "'";
log.error(msg, appMgtEx);
Assert.fail(msg, appMgtEx);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java
index aba662e3ef..ba0a666846 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java
@@ -72,7 +72,7 @@ public abstract class BaseDeviceManagementTest {
return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}
- private void initializeCarbonContext(){
+ private void initializeCarbonContext() {
if (System.getProperty("carbon.home") == null) {
File file = new File("src/test/resources/carbon-home");
@@ -129,11 +129,12 @@ public abstract class BaseDeviceManagementTest {
conn = getDataSource().getConnection();
conn.setAutoCommit(false);
- this.cleanupEnrolmentData(conn);
- this.cleanApplicationMappingData(conn);
- this.cleanApplicationData(conn);
- this.cleanupDeviceData(conn);
- this.cleanupDeviceTypeData(conn);
+ //TODO:FIX ME
+// this.cleanupEnrolmentData(conn);
+// this.cleanApplicationMappingData(conn);
+// this.cleanApplicationData(conn);
+// this.cleanupDeviceData(conn);
+// this.cleanupDeviceTypeData(conn);
conn.commit();
} catch (SQLException e) {
@@ -158,64 +159,34 @@ public abstract class BaseDeviceManagementTest {
}
}
- private void cleanApplicationMappingData(Connection conn) throws SQLException{
- PreparedStatement stmt = null;
- try {
- stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_APPLICATION_MAPPING");
+ private void cleanApplicationMappingData(Connection conn) throws SQLException {
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_APPLICATION_MAPPING")) {
stmt.execute();
- } finally {
- if (stmt != null) {
- stmt.close();
- }
}
}
- private void cleanApplicationData(Connection conn) throws SQLException{
- PreparedStatement stmt = null;
- try {
- stmt = conn.prepareStatement("DELETE FROM DM_APPLICATION");
+ private void cleanApplicationData(Connection conn) throws SQLException {
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_APPLICATION")) {
stmt.execute();
- } finally {
- if (stmt != null) {
- stmt.close();
- }
}
}
private void cleanupEnrolmentData(Connection conn) throws SQLException {
- PreparedStatement stmt = null;
- try {
- stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT");
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT")) {
stmt.execute();
- } finally {
- if (stmt != null) {
- stmt.close();
- }
}
}
private void cleanupDeviceData(Connection conn) throws SQLException {
- PreparedStatement stmt = null;
- try {
- stmt = conn.prepareStatement("DELETE FROM DM_DEVICE");
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE")) {
stmt.execute();
- } finally {
- if (stmt != null) {
- stmt.close();
- }
}
}
private void cleanupDeviceTypeData(Connection conn) throws SQLException {
- PreparedStatement stmt = null;
- try {
- stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE");
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE")) {
stmt.execute();
- } finally {
- if (stmt != null) {
- stmt.close();
- }
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java
index 603954ea76..0798f28115 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java
@@ -26,6 +26,7 @@ import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
+import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.TestUtils;
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
@@ -50,12 +51,18 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
public void testAddDeviceTypeTest() {
DeviceType deviceType = TestDataHolder.generateDeviceTypeData(TestDataHolder.TEST_DEVICE_TYPE);
try {
- DeviceManagementDAOFactory.openConnection();
+ DeviceManagementDAOFactory.beginTransaction();
deviceTypeDAO.addDeviceType(deviceType);
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while adding device type '" + deviceType.getName() + "'";
log.error(msg, e);
Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction to persist device type '" +
+ deviceType.getName() + "'";
+ log.error(msg, e);
+ Assert.fail(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -75,21 +82,26 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
@Test(dependsOnMethods = {"testAddDeviceTypeTest"})
public void testAddDeviceTest() {
-
int tenantId = TestDataHolder.SUPER_TENANT_ID;
Device device = TestDataHolder.generateDummyDeviceData(TestDataHolder.TEST_DEVICE_TYPE);
try {
- DeviceManagementDAOFactory.openConnection();
+ DeviceManagementDAOFactory.beginTransaction();
int deviceId = deviceDAO.addDevice(TestDataHolder.initialTestDeviceType.getId(), device, tenantId);
device.setId(deviceId);
deviceDAO.addEnrollment(device, tenantId);
+ DeviceManagementDAOFactory.commitTransaction();
TestDataHolder.initialTestDevice = device;
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while adding '" + device.getType() + "' device with the identifier '" +
device.getDeviceIdentifier() + "'";
log.error(msg, e);
Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction";
+ log.error(msg, e);
+ Assert.fail(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -164,14 +176,19 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
Device device = TestDataHolder.initialTestDevice;
try {
- DeviceManagementDAOFactory.openConnection();
+ DeviceManagementDAOFactory.beginTransaction();
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
deviceDAO.setEnrolmentStatus(deviceId, device.getEnrolmentInfo().getOwner(), Status.ACTIVE,
TestDataHolder.SUPER_TENANT_ID);
- } catch (DeviceManagementDAOException | SQLException e) {
+ } catch (DeviceManagementDAOException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while setting enrolment status";
log.error(msg, e);
Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction";
+ log.error(msg, e);
+ Assert.fail(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml
index cf107283b8..4622a58873 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml
@@ -37,4 +37,4 @@
-
\ No newline at end of file
+
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java
index 121454e77a..6087207db1 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java
@@ -42,6 +42,8 @@ public class Policy implements Comparable, Serializable {
private String ownershipType; // Ownership type (COPE, BYOD, CPE)
private List devices; // Individual devices this policy should be applied
private List users;
+ private boolean active;
+ private boolean updated;
/* Compliance data*/
@@ -53,19 +55,6 @@ public class Policy implements Comparable, Serializable {
private List policyCriterias;
- /*These are related to time based policies*/
-
-// private int startTime; // Start time to apply the policy.
-// private int endTime; // After this time policy will not be applied
-// private Date startDate; // Start date to apply the policy
-// private Date endDate; // After this date policy will not be applied.
-
-
- /*These are related to location based policies*/
-
- // private String latitude; // Latitude
-// private String longitude; // Longitude
-//
private int tenantId;
private int profileId;
@@ -163,6 +152,24 @@ public class Policy implements Comparable, Serializable {
this.users = users;
}
+ @XmlElement
+ public boolean isActive() {
+ return active;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ @XmlElement
+ public boolean isUpdated() {
+ return updated;
+ }
+
+ public void setUpdated(boolean updated) {
+ this.updated = updated;
+ }
+
@XmlElement
public List getPolicyCriterias() {
return policyCriterias;
@@ -172,6 +179,7 @@ public class Policy implements Comparable, Serializable {
this.policyCriterias = policyCriterias;
}
+ @XmlElement
public String getCompliance() {
return Compliance;
}
@@ -180,59 +188,6 @@ public class Policy implements Comparable, Serializable {
Compliance = compliance;
}
- // public int getStartTime() {
-// return startTime;
-// }
-//
-// public void setStartTime(int startTime) {
-// this.startTime = startTime;
-// }
-//
-// @XmlElement
-// public int getEndTime() {
-// return endTime;
-// }
-//
-// public void setEndTime(int endTime) {
-// this.endTime = endTime;
-// }
-//
-// @XmlElement
-// public Date getStartDate() {
-// return startDate;
-// }
-//
-// public void setStartDate(Date startDate) {
-// this.startDate = startDate;
-// }
-//
-// @XmlElement
-// public Date getEndDate() {
-// return endDate;
-// }
-//
-// public void setEndDate(Date endDate) {
-// this.endDate = endDate;
-// }
-//
-// @XmlElement
-// public String getLatitude() {
-// return latitude;
-// }
-//
-// public void setLatitude(String latitude) {
-// this.latitude = latitude;
-// }
-//
-// @XmlElement
-// public String getLongitude() {
-// return longitude;
-// }
-//
-// public void setLongitude(String longitude) {
-// this.longitude = longitude;
-// }
-
@XmlElement
public Map getAttributes() {
return attributes;
@@ -252,18 +207,6 @@ public class Policy implements Comparable, Serializable {
}
- /* static final Comparator PRIORITY_ORDER =
- new Comparator() {
- public int compare(Policy p1, Policy p2) {
- int dateCmp = new Integer(p2.getId()).compareTo(new Integer(p1.getId()));
- if (dateCmp != 0)
- return dateCmp;
-
- return (p1.getId() < p2.getId() ? -1 :
- (p1.getId() == p2.getId() ? 0 : 1));
- }
- };*/
-
@Override
public int compareTo(Policy o) {
if (this.priorityId == o.priorityId)
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java
index f59e722d5f..2774c3bf4f 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java
@@ -40,9 +40,15 @@ public interface PolicyAdministratorPoint {
boolean updatePolicyPriorities(List policies) throws PolicyManagementException;
+ void activatePolicy(int policyId) throws PolicyManagementException;
+
+ void inactivatePolicy(int policyId) throws PolicyManagementException;
+
boolean deletePolicy(Policy policy) throws PolicyManagementException;
boolean deletePolicy(int policyId) throws PolicyManagementException;
+ void publishChanges() throws PolicyManagementException;
+
/**
* This method adds a policy per device which should be implemented by the related plugins.
*/
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java
index b636d5d9c3..44303782ff 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java
@@ -23,6 +23,8 @@ import java.util.List;
public interface PolicyFilter {
+ List filterActivePolicies(List policies);
+
List filterRolesBasedPolicies(String roles[], List policies);
List filterOwnershipTypeBasedPolicies(String ownershipType, List policies);
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml
index c818c48bef..a2333b475d 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml
@@ -55,8 +55,6 @@
Policy Management Core Bundle
org.wso2.carbon.policy.mgt.core.internal
- org.apache.axis2.*;
- version="${axis2.osgi.version.range}",
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
@@ -144,6 +142,15 @@
org.wso2.carbon.ntask.core
+
+
+ org.wso2.carbon
+ org.wso2.carbon.registry.api
+
+
+ org.wso2.carbon
+ org.wso2.carbon.registry.core
+
org.wso2.carbon.devicemgt
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java
index 573df93e38..63b3a666c7 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java
@@ -19,7 +19,8 @@
package org.wso2.carbon.policy.mgt.core.cache;
-import org.wso2.carbon.device.mgt.core.policy.mgt.policy.Policy;
+import org.wso2.carbon.policy.mgt.common.Policy;
+import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import java.util.List;
@@ -29,7 +30,9 @@ public interface PolicyCacheManager {
void updateAllPolicies(List policies);
- List getAllPolicies();
+ List getAllPolicies() throws PolicyManagementException;
+
+ void rePopulateCache() throws PolicyManagementException;
void removeAllPolicies();
@@ -37,9 +40,11 @@ public interface PolicyCacheManager {
void updatePolicy(Policy policy);
+ void updatePolicy(int policyId) throws PolicyManagementException;
+
void removePolicy(int policyId);
- Policy getPolicy(int policyId);
+ Policy getPolicy(int policyId) throws PolicyManagementException;
void addPolicyToDevice(int deviceId, int policyId);
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java
index d7c8046755..677b30920d 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java
@@ -19,51 +19,145 @@
package org.wso2.carbon.policy.mgt.core.cache.impl;
-import org.wso2.carbon.device.mgt.core.policy.mgt.policy.Policy;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.policy.mgt.common.Policy;
+import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager;
+import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
+import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Set;
public class PolicyCacheManagerImpl implements PolicyCacheManager {
+ private static final Log log = LogFactory.getLog(PolicyCacheManagerImpl.class);
+
+ private static HashMap> tenantedPolicyMap = new HashMap<>();
+
+ private static PolicyCacheManagerImpl policyCacheManager;
+
+ private PolicyCacheManagerImpl() {
+ }
+
+ public static PolicyCacheManager getInstance() {
+ if (policyCacheManager == null) {
+ synchronized (PolicyCacheManagerImpl.class) {
+ if (policyCacheManager == null) {
+ policyCacheManager = new PolicyCacheManagerImpl();
+ }
+ }
+ }
+ return policyCacheManager;
+ }
+
@Override
public void addAllPolicies(List policies) {
+ HashMap map = this.getTenantRelatedMap();
+ if (map.isEmpty()) {
+ for (Policy policy : policies) {
+ map.put(policy.getId(), policy);
+ }
+ }
}
@Override
public void updateAllPolicies(List policies) {
+ HashMap map = this.getTenantRelatedMap();
+ map.clear();
+ if (map.isEmpty()) {
+ for (Policy policy : policies) {
+ map.put(policy.getId(), policy);
+ }
+ }
+ }
+ @Override
+ public List getAllPolicies() throws PolicyManagementException {
+ HashMap map = this.getTenantRelatedMap();
+ if (map.isEmpty()) {
+ PolicyManager policyManager = new PolicyManagerImpl();
+ this.addAllPolicies(policyManager.getPolicies());
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("No of policies stored in the cache .. : " + map.size());
+
+ Set keySet = map.keySet();
+ for (Integer x : keySet) {
+ log.debug("Policy id in maps .. : " + map.get(x).getId() + " policy name : " + map.get(x).
+ getPolicyName() + " Activated : " + map.get(x).isActive());
+ }
+ }
+ return new ArrayList<>(map.values());
}
@Override
- public List getAllPolicies() {
- return null;
+ public void rePopulateCache() throws PolicyManagementException {
+
+ this.removeAllPolicies();
+ this.getAllPolicies();
}
@Override
public void removeAllPolicies() {
-
+ HashMap map = this.getTenantRelatedMap();
+ map.clear();
}
@Override
public void addPolicy(Policy policy) {
-
+ HashMap map = this.getTenantRelatedMap();
+ if (!map.containsKey(policy.getId())) {
+ map.put(policy.getId(), policy);
+ } else {
+ log.warn("Policy id (" + policy.getId() + ") already exist in the map. hence not attempted to store.");
+ }
}
@Override
public void updatePolicy(Policy policy) {
+ HashMap map = this.getTenantRelatedMap();
+ if (map.containsKey(policy.getId())) {
+ map.remove(policy.getId());
+ map.put(policy.getId(), policy);
+ }
+ }
+ @Override
+ public void updatePolicy(int policyId) throws PolicyManagementException {
+ HashMap map = this.getTenantRelatedMap();
+ if (map.containsKey(policyId)) {
+ this.removePolicy(policyId);
+ }
+ PolicyManager policyManager = new PolicyManagerImpl();
+ Policy policy = policyManager.getPolicy(policyId);
+ map.put(policyId, policy);
}
@Override
public void removePolicy(int policyId) {
-
+ HashMap map = this.getTenantRelatedMap();
+ if (map.containsKey(policyId)) {
+ map.remove(policyId);
+ } else {
+ log.warn("Policy id (" + policyId + ") does not exist in the cache. Hence not removed.");
+ }
}
@Override
- public Policy getPolicy(int policyId) {
- return null;
+ public Policy getPolicy(int policyId) throws PolicyManagementException {
+ HashMap map = this.getTenantRelatedMap();
+ if (!map.containsKey(policyId)) {
+ this.removeAllPolicies();
+ this.getAllPolicies();
+ }
+ return map.get(policyId);
+
}
@Override
@@ -80,4 +174,14 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
public int getPolicyIdOfDevice(int deviceId) {
return 0;
}
+
+ private HashMap getTenantRelatedMap(){
+
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+ if(!tenantedPolicyMap.containsKey(tenantId)){
+ HashMap policyMap = new HashMap<>();
+ tenantedPolicyMap.put(tenantId, policyMap);
+ }
+ return tenantedPolicyMap.get(tenantId);
+ }
}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java
index 071612fdd2..9f5ba5b255 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java
@@ -42,6 +42,16 @@ public interface PolicyDAO {
boolean updatePolicyPriorities(List policies) throws PolicyManagerDAOException;
+ void activatePolicy(int policyId) throws PolicyManagerDAOException;
+
+ void activatePolicies(List policyIds) throws PolicyManagerDAOException;
+
+ void markPoliciesAsUpdated(List policyIds) throws PolicyManagerDAOException;
+
+ void inactivatePolicy(int policyId) throws PolicyManagerDAOException;
+
+ HashMap getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException;
+
Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException;
Criterion updateCriterion(Criterion criteria) throws PolicyManagerDAOException;
@@ -64,6 +74,12 @@ public interface PolicyDAO {
Policy updatePolicy(Policy policy) throws PolicyManagerDAOException;
+ void recordUpdatedPolicy(Policy policy) throws PolicyManagerDAOException;
+
+ void recordUpdatedPolicies(List policies) throws PolicyManagerDAOException;
+
+ void removeRecordsAboutUpdatedPolicies() throws PolicyManagerDAOException;
+
Policy getPolicy(int policyId) throws PolicyManagerDAOException;
Policy getPolicyByProfileID(int profileId) throws PolicyManagerDAOException;
@@ -90,21 +106,23 @@ public interface PolicyDAO {
List getPolicyAppliedUsers(int policyId) throws PolicyManagerDAOException;
- void addEffectivePolicyToDevice(int deviceId, Policy policy)
+ void addEffectivePolicyToDevice(int deviceId, int enrolmentId, Policy policy)
throws PolicyManagerDAOException;
- void setPolicyApplied(int deviceId) throws PolicyManagerDAOException;
+ void setPolicyApplied(int deviceId, int enrollmentId) throws PolicyManagerDAOException;
- void updateEffectivePolicyToDevice(int deviceId, Policy policy)
+ void updateEffectivePolicyToDevice(int deviceId, int enrolmentId, Policy policy)
throws PolicyManagerDAOException;
- boolean checkPolicyAvailable(int deviceId) throws PolicyManagerDAOException;
+ boolean checkPolicyAvailable(int deviceId, int enrollmentId) throws PolicyManagerDAOException;
int getPolicyCount() throws PolicyManagerDAOException;
- int getAppliedPolicyId(int deviceId) throws PolicyManagerDAOException;
+ int getAppliedPolicyId(int deviceId, int enrollmentId) throws PolicyManagerDAOException;
- Policy getAppliedPolicy(int deviceId) throws PolicyManagerDAOException;
+ Policy getAppliedPolicy(int deviceId, int enrollmentId) throws PolicyManagerDAOException;
HashMap getAppliedPolicyIds(List deviceIds) throws PolicyManagerDAOException;
- }
+
+ HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException;
+}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
index b488ddde40..0b00f90b14 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
@@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.policy.mgt.core.dao.impl.FeatureDAOImpl;
@@ -38,7 +39,7 @@ public class PolicyManagementDAOFactory {
private static DataSource dataSource;
private static final Log log = LogFactory.getLog(PolicyManagementDAOFactory.class);
- private static ThreadLocal currentConnection = new ThreadLocal();
+ private static ThreadLocal currentConnection = new ThreadLocal<>();
public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config);
@@ -48,13 +49,6 @@ public class PolicyManagementDAOFactory {
dataSource = dtSource;
}
- public static DataSource getDataSource() {
- if (dataSource != null) {
- return dataSource;
- }
- throw new RuntimeException("Data source is not yet configured.");
- }
-
public static PolicyDAO getPolicyDAO() {
return new PolicyDAOImpl();
}
@@ -81,7 +75,7 @@ public class PolicyManagementDAOFactory {
DataSource dataSource = null;
if (config == null) {
throw new RuntimeException("Device Management Repository data source configuration is null and thus," +
- " is not initialized");
+ " is not initialized");
}
JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition();
if (jndiConfig != null) {
@@ -91,7 +85,7 @@ public class PolicyManagementDAOFactory {
List jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
- Hashtable