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..de17582905 --- /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,452 @@ +/* + * 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.util.ConfigurationUtil; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.util.CommonUtil; + +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.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()); + + 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 static X509Certificate generateCertificateFromCSR(PrivateKey privateKey, + PKCS10CertificationRequest request, + String issueSubject) + throws KeystoreException { + + CommonUtil commonUtil = new CommonUtil(); + Date validityBeginDate = commonUtil.getValidityStartDate(); + Date validityEndDate = commonUtil.getValidityEndDate(); + + X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( + new X500Name(issueSubject), BigInteger.valueOf(System.currentTimeMillis()), + validityBeginDate, validityEndDate, request.getSubject(), 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)); + } 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); + } catch (KeystoreException e) { + String errorMsg = "Keystore reading error occurred when handling profile request"; + 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..684b91b336 --- /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,186 @@ +/* + * 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.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 = "Certificate expired 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; + } + + KeyStore loadMDMKeyStore() throws KeystoreException { + return loadKeyStore(ConfigurationUtil.CERTIFICATE_KEYSTORE, ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE, + ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD); + } + + public Certificate getCACertificate() throws KeystoreException { + + KeyStore keystore = loadMDMKeyStore(); + 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 = loadMDMKeyStore(); + 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 = loadMDMKeyStore(); + 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 = loadMDMKeyStore(); + 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..5996028f7d --- /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,57 @@ +/* + * 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.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(CertificateManagementServiceImpl.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..a9a55d9b12 --- /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[] emmConfigEntryNames = { 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 readEMMConfigurations() throws KeystoreException { + + String emmConfLocation = 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(emmConfLocation); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + document = documentBuilder.parse(fXmlFile); + } catch (ParserConfigurationException e) { + throw new KeystoreException("Error parsing configuration in ios-config.xml file"); + } catch (SAXException e) { + throw new KeystoreException("SAX exception in ios-config.xml file"); + } catch (IOException e) { + throw new KeystoreException("Error reading ios-config.xml file"); + } + + for (String configEntry : emmConfigEntryNames) { + NodeList elements = document.getElementsByTagName(configEntry); + if (elements != null && elements.getLength() > 0) { + configMap.put(configEntry, elements.item(0).getTextContent()); + } + } + + String emmKeyStoreLocation = replaceCarbonHomeEnvEntry(configMap.get(PATH_CERTIFICATE_KEYSTORE)); + if (emmKeyStoreLocation != null) { + configMap.put(PATH_CERTIFICATE_KEYSTORE, emmKeyStoreLocation); + } + } + + return configMap; + } + + public static String getConfigEntry(final String entry) throws KeystoreException { + + Map configurationMap = readEMMConfigurations(); + 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..8d12f336fe --- /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,101 @@ +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 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 { + 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 ", 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/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/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/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 b39b40fa4f..6ec2eb26d5 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 @@ -113,7 +113,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 " + @@ -179,7 +179,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); @@ -210,7 +210,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 = ?"; @@ -475,6 +475,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()); @@ -493,7 +494,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 = ?"; 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..de7b8730b7 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 @@ -81,6 +81,7 @@ public class OperationManagerImpl implements OperationManager { } 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 '" + 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/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index 68aa6fa8bd..e5033c357c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -119,17 +119,22 @@ public class PolicyDAOImpl implements PolicyDAO { PreparedStatement stmt = null; try { conn = this.getConnection(); - String query = "INSERT INTO DM_DEVICE_POLICY (DEVICE_ID, POLICY_ID) VALUES (?, ?)"; + String query = "INSERT INTO DM_DEVICE_POLICY (DEVICE_ID, POLICY_ID, ENROLMENT_ID, DEVICE) VALUES (?, ?, " + + "?, ?)"; stmt = conn.prepareStatement(query); for (Device device : devices) { stmt.setInt(1, device.getId()); stmt.setInt(2, policy.getId()); + stmt.setInt(3, device.getEnrolmentInfo().getId()); + stmt.setBytes(4, PolicyManagerUtil.getBytes(device)); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while adding the device ids with policy to " + "database", e); + } catch (IOException e) { + throw new PolicyManagerDAOException("Error occurred while getting the byte array from device.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } @@ -144,13 +149,14 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "UPDATE DM_POLICY SET PRIORITY = ? WHERE ID = ? AND TENANT_ID = ?"; + String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (Policy policy : policies) { stmt.setInt(1, policy.getPriorityId()); - stmt.setInt(2, policy.getId()); - stmt.setInt(3, tenantId); + stmt.setInt(2, 1); + stmt.setInt(3, policy.getId()); + stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); @@ -162,6 +168,137 @@ public class PolicyDAOImpl implements PolicyDAO { return true; } + @Override + public void activatePolicy(int policyId) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, 1); + stmt.setInt(2, 1); + stmt.setInt(3, policyId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating policy id (" + policyId + + ") in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + + } + + @Override + public void activatePolicies(List policyIds) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + for (int policyId : policyIds) { + stmt.setInt(1, 1); + stmt.setInt(2, 1); + stmt.setInt(3, policyId); + stmt.setInt(4, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void markPoliciesAsUpdated(List policyIds) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + for (int policyId : policyIds) { + stmt.setInt(1, 0); + stmt.setInt(2, policyId); + stmt.setInt(3, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void inactivatePolicy(int policyId) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET ACTIVE = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, 0); + stmt.setInt(2, 1); + stmt.setInt(3, policyId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating policy id (" + policyId + + ") in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public HashMap getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + HashMap map = new HashMap<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ?"; + stmt.setInt(1, tenantId); + stmt = conn.prepareStatement(query); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + map.put(resultSet.getInt("POLICY_ID"), resultSet.getInt("DEVICE_TYPE_ID")); + } + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while reading the changed policies form database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return map; + } + @Override public Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException { @@ -477,15 +614,16 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "UPDATE DM_POLICY SET NAME= ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?" + - " WHERE ID = ? AND TENANT_ID = ?"; + String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," + + " UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, policy.getPolicyName()); stmt.setInt(2, policy.getProfile().getProfileId()); stmt.setInt(3, policy.getPriorityId()); stmt.setString(4, policy.getCompliance()); - stmt.setInt(5, policy.getId()); - stmt.setInt(6, tenantId); + stmt.setInt(5, 1); + stmt.setInt(6, policy.getId()); + stmt.setInt(7, tenantId); stmt.executeUpdate(); } catch (SQLException e) { @@ -497,6 +635,77 @@ public class PolicyDAOImpl implements PolicyDAO { return policy; } + @Override + public void recordUpdatedPolicy(Policy policy) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "INSERT INTO DM_POLICY_CHANGE_MGT (POLICY_ID, DEVICE_TYPE_ID, TENANT_ID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, policy.getId()); + stmt.setInt(2, policy.getProfile().getDeviceType().getId()); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating the policy changes in the database for" + + " " + + "policy name (" + policy.getPolicyName() + ")", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void recordUpdatedPolicies(List policies) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "INSERT INTO DM_POLICY_CHANGE_MGT (POLICY_ID, DEVICE_TYPE_ID, TENANT_ID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(query); + for (Policy policy : policies) { + stmt.setInt(1, policy.getId()); + stmt.setInt(2, policy.getProfile().getDeviceType().getId()); + stmt.setInt(3, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating the policy changes in the database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void removeRecordsAboutUpdatedPolicies() throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "DELETE FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ? "; + stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while deleting the policy changes in the database for" + + " " + + "tenant id (" + tenantId + ")", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + + } + @Override public Policy getPolicy(int policyId) throws PolicyManagerDAOException { Connection conn; @@ -585,6 +794,8 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); policies.add(policy); } return policies; @@ -675,7 +886,8 @@ public class PolicyDAOImpl implements PolicyDAO { @Override - public void addEffectivePolicyToDevice(int deviceId, Policy policy) throws PolicyManagerDAOException { + public void addEffectivePolicyToDevice(int deviceId, int enrolmentId, Policy policy) throws + PolicyManagerDAOException { Connection conn; PreparedStatement stmt = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); @@ -683,7 +895,7 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "INSERT INTO DM_DEVICE_POLICY_APPLIED (DEVICE_ID, POLICY_ID, POLICY_CONTENT, " + - "CREATED_TIME, UPDATED_TIME, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)"; + "CREATED_TIME, UPDATED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, policy.getId()); @@ -691,6 +903,7 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setTimestamp(4, currentTimestamp); stmt.setTimestamp(5, currentTimestamp); stmt.setInt(6, tenantId); + stmt.setInt(7, enrolmentId); stmt.executeUpdate(); } catch (SQLException | IOException e) { throw new PolicyManagerDAOException("Error occurred while adding the evaluated feature list to device", e); @@ -701,7 +914,7 @@ public class PolicyDAOImpl implements PolicyDAO { } @Override - public void setPolicyApplied(int deviceId) throws PolicyManagerDAOException { + public void setPolicyApplied(int deviceId, int enrollmentId) throws PolicyManagerDAOException { Connection conn; PreparedStatement stmt = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); @@ -709,12 +922,13 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "UPDATE DM_DEVICE_POLICY_APPLIED SET APPLIED_TIME = ?, APPLIED = ? WHERE DEVICE_ID = ? AND" + - " TENANT_ID = ?"; + " TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setTimestamp(1, currentTimestamp); stmt.setBoolean(2, true); stmt.setInt(3, deviceId); stmt.setInt(4, tenantId); + stmt.setInt(5, enrollmentId); stmt.executeUpdate(); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while updating applied policy to device (" + @@ -726,7 +940,8 @@ public class PolicyDAOImpl implements PolicyDAO { @Override - public void updateEffectivePolicyToDevice(int deviceId, Policy policy) throws PolicyManagerDAOException { + public void updateEffectivePolicyToDevice(int deviceId, int enrolmentId, Policy policy) throws + PolicyManagerDAOException { Connection conn; PreparedStatement stmt = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); @@ -734,7 +949,7 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "UPDATE DM_DEVICE_POLICY_APPLIED SET POLICY_ID = ?, POLICY_CONTENT = ?, UPDATED_TIME = ?, " + - "APPLIED = ? WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + "APPLIED = ? WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, policy.getId()); stmt.setBytes(2, PolicyManagerUtil.getBytes(policy)); @@ -742,6 +957,7 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setBoolean(4, false); stmt.setInt(5, deviceId); stmt.setInt(6, tenantId); + stmt.setInt(7, enrolmentId); stmt.executeUpdate(); } catch (SQLException | IOException e) { @@ -753,7 +969,7 @@ public class PolicyDAOImpl implements PolicyDAO { } @Override - public boolean checkPolicyAvailable(int deviceId) throws PolicyManagerDAOException { + public boolean checkPolicyAvailable(int deviceId, int enrollmentId) throws PolicyManagerDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -761,10 +977,12 @@ public class PolicyDAOImpl implements PolicyDAO { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); - String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ? AND " + + "ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); + stmt.setInt(3, enrollmentId); resultSet = stmt.executeQuery(); exist = resultSet.next(); } catch (SQLException e) { @@ -884,12 +1102,16 @@ public class PolicyDAOImpl implements PolicyDAO { stmt = conn.prepareStatement(query); stmt.setInt(1, policyId); stmt.setInt(2, tenantId); - stmt.executeUpdate(); + int deleted = stmt.executeUpdate(); if (log.isDebugEnabled()) { log.debug("Policy (" + policyId + ") delete from database."); } - return true; + if (deleted > 0) { + return true; + } else { + return false; + } } catch (SQLException e) { throw new PolicyManagerDAOException("Unable to delete the policy (" + policyId + ") from database", e); } finally { @@ -948,8 +1170,9 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE)" + - " VALUES (?, ?, ?, ?, ?, ?)"; + String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," + + " " + + "UPDATED, ACTIVE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt.setString(1, policy.getPolicyName()); @@ -958,6 +1181,8 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setInt(4, readHighestPriorityOfPolicies()); stmt.setString(5, policy.getCompliance()); stmt.setString(6, policy.getOwnershipType()); + stmt.setInt(7, 0); + stmt.setInt(8, 0); int affectedRows = stmt.executeUpdate(); @@ -1069,17 +1294,18 @@ public class PolicyDAOImpl implements PolicyDAO { } @Override - public int getAppliedPolicyId(int deviceId) throws PolicyManagerDAOException { + public int getAppliedPolicyId(int deviceId, int enrollmentId) throws PolicyManagerDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); - String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); + stmt.setInt(3, enrollmentId); resultSet = stmt.executeQuery(); if (resultSet.next()) { @@ -1094,7 +1320,7 @@ public class PolicyDAOImpl implements PolicyDAO { } @Override - public Policy getAppliedPolicy(int deviceId) throws PolicyManagerDAOException { + public Policy getAppliedPolicy(int deviceId, int enrollmentId) throws PolicyManagerDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -1102,10 +1328,12 @@ public class PolicyDAOImpl implements PolicyDAO { Policy policy = null; try { conn = this.getConnection(); - String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ? AND " + + "ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); + stmt.setInt(3, enrollmentId); resultSet = stmt.executeQuery(); while (resultSet.next()) { @@ -1183,4 +1411,31 @@ public class PolicyDAOImpl implements PolicyDAO { return devicePolicyIds; } + @Override + public HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + HashMap devicePolicyIds = new HashMap<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + devicePolicyIds.put(resultSet.getInt("DEVICE_ID"), resultSet.getInt("POLICY_ID")); + } + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while getting the applied policy", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return devicePolicyIds; + } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java index d8164cffe4..8565d5db0f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java @@ -90,19 +90,19 @@ public class ProfileDAOImpl implements ProfileDAO { Connection conn; PreparedStatement stmt = null; - ResultSet generatedKeys = null; + // ResultSet generatedKeys = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); - String query = "UPDATE DM_PROFILE SET PROFILE_NAME = ? ,TENANT_ID = ?, DEVICE_TYPE_ID = ? , UPDATED_TIME = ? " + - "WHERE ID = ?"; - stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); - stmt.setString(1, profile.getProfileName()); - stmt.setInt(2, tenantId); - stmt.setLong(3, profile.getDeviceType().getId()); - stmt.setTimestamp(4, profile.getUpdatedDate()); - stmt.setInt(5, profile.getProfileId()); + String query = "UPDATE DM_PROFILE SET PROFILE_NAME = ? , DEVICE_TYPE_ID = ? , UPDATED_TIME = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setString(1, profile.getProfileName()); + stmt.setLong(2, profile.getDeviceType().getId()); + stmt.setTimestamp(3, profile.getUpdatedDate()); + stmt.setInt(4, profile.getProfileId()); + stmt.setInt(5, tenantId); int affectedRows = stmt.executeUpdate(); @@ -110,22 +110,22 @@ public class ProfileDAOImpl implements ProfileDAO { String msg = "No rows are updated on the profile table."; log.debug(msg); } - generatedKeys = stmt.getGeneratedKeys(); - - if (generatedKeys.next()) { - profile.setProfileId(generatedKeys.getInt(1)); - } - // Checking the profile id here, because profile id could have been passed from the calling method. - if (profile.getProfileId() == 0) { - throw new RuntimeException("Profile id is 0, this could be an issue."); - } +// generatedKeys = stmt.getGeneratedKeys(); +// +// if (generatedKeys.next()) { +// profile.setProfileId(generatedKeys.getInt(1)); +// } +// // Checking the profile id here, because profile id could have been passed from the calling method. +// if (profile.getProfileId() == 0) { +// throw new RuntimeException("Profile id is 0, this could be an issue."); +// } } catch (SQLException e) { String msg = "Error occurred while updating the profile (" + profile.getProfileName() + ") in database."; log.error(msg, e); throw new ProfileManagerDAOException(msg, e); } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); + PolicyManagementDAOUtil.cleanupResources(stmt, null); } return profile; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java new file mode 100644 index 0000000000..ad9f58654c --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -0,0 +1,96 @@ +/* + * 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.policy.mgt.core.enforcement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +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.Map; + +public class DelegationTask implements Task { + + private static final Log log = LogFactory.getLog(DelegationTask.class); + + @Override + public void setProperties(Map map) { + + } + + @Override + public void init() { + + } + + @Override + public void execute() { + + try { + PolicyManager policyManager = new PolicyManagerImpl(); + List deviceTypes = policyManager.applyChangesMadeToPolicies(); + + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + + if (log.isDebugEnabled()) { + log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size()); + } + if (!deviceTypes.isEmpty()) { + DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() + .getDeviceManagementService(); + List devices = new ArrayList<>(); + for (DeviceType deviceType : deviceTypes) { + try { + devices.addAll(service.getAllDevices(deviceType.getName())); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while taking the devices", e); + } + } + HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); + List toBeNotified = new ArrayList<>(); + + for (Device device : devices) { + if (deviceIdPolicy.containsKey(device.getId())) { + toBeNotified.add(device); + } + } + if (!toBeNotified.isEmpty()) { + PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); + enforcementDelegator.delegate(); + } + } + + } catch (PolicyManagementException e) { + log.error("Error occurred while getting the policies applied to devices.", e); + } catch (PolicyDelegationException e) { + log.error("Error occurred while running the delegation task.", e); + } + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java index f1e7a52e12..218fe0398e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java @@ -18,7 +18,6 @@ */ package org.wso2.carbon.policy.mgt.core.enforcement; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.policy.mgt.common.Policy; @@ -26,6 +25,10 @@ import java.util.List; public interface PolicyEnforcementDelegator { - void delegate(Policy policy, List devices) throws PolicyDelegationException; + void delegate() throws PolicyDelegationException; + + Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException; + + void addPolicyOperation(List deviceIdentifiers, Policy policy) throws PolicyDelegationException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index ab03f36626..3e3b605c85 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -18,33 +18,93 @@ */ package org.wso2.carbon.policy.mgt.core.enforcement; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.policy.mgt.common.Policy; +import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import java.util.ArrayList; import java.util.List; -public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator { +public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator{ - private OperationManager operationManager = new OperationManagerImpl(); + private static final Log log = LogFactory.getLog(PolicyEnforcementDelegatorImpl.class); - @Override - public void delegate(Policy policy, List devices) throws PolicyDelegationException { - try { - List deviceIds = new ArrayList<>(); + private List devices; + + public PolicyEnforcementDelegatorImpl(List devices) { + + log.info("Policy re-enforcing stared due to change of the policies."); + + if (log.isDebugEnabled()) { for (Device device : devices) { - deviceIds.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + log.debug("Policy re-enforcing for device :" + device.getDeviceIdentifier() + " - Type : " + + device.getType()); + } + } + this.devices = devices; + + } + + @Override + public void delegate() throws PolicyDelegationException { + + for (Device device : devices) { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(device.getDeviceIdentifier()); + identifier.setType(device.getType()); + + Policy policy = this.getEffectivePolicy(identifier); + + if (policy != null) { + List deviceIdentifiers = new ArrayList<>(); + deviceIdentifiers.add(identifier); + this.addPolicyOperation(deviceIdentifiers, policy); } - operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIds); + + } + } + + @Override + public Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException { + + try { + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + return policyManagerService.getPEP().getEffectivePolicy(identifier); + //return PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().getEffectivePolicy(identifier); + } catch (PolicyEvaluationException e) { + String msg = "Error occurred while retrieving the effective policy for devices."; + log.error(msg, e); + throw new PolicyDelegationException(msg, e); + } catch (PolicyManagementException e) { + String msg = "Error occurred while retrieving the effective policy for devices."; + log.error(msg, e); + throw new PolicyDelegationException(msg, e); + } + } + + @Override + public void addPolicyOperation(List deviceIdentifiers, Policy policy) throws + PolicyDelegationException { + + try { + OperationManager operationManager = new OperationManagerImpl(); + operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIdentifiers); } catch (OperationManagementException e) { - throw new PolicyDelegationException("Error occurred while delegating policy information to " + - "the respective enforcement points", e); + String msg = "Error occurred while adding the operation to device."; + log.error(msg, e); + throw new PolicyDelegationException(msg, e); } + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 971d2e268a..d78e6b16e2 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -166,10 +166,8 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { } } catch (OperationManagementException e) { - String msg = "Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " + - deviceIdentifier.getType(); - log.error(msg, e); - throw new PolicyComplianceException(msg, e); + throw new PolicyComplianceException("Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(), e); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index e406e9fbaf..b17fd2bd6e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -20,24 +20,27 @@ package org.wso2.carbon.policy.mgt.core.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.policy.mgt.common.FeatureManagementException; -import org.wso2.carbon.policy.mgt.common.Policy; -import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; -import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.policy.mgt.common.Profile; -import org.wso2.carbon.policy.mgt.common.ProfileManagementException; -import org.wso2.carbon.policy.mgt.core.enforcement.PolicyDelegationException; -import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegator; -import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegatorImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskManager; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; +import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { @@ -46,13 +49,15 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { private PolicyManager policyManager; private ProfileManager profileManager; private FeatureManager featureManager; - private PolicyEnforcementDelegator delegator; + private PolicyCacheManager cacheManager; + // private PolicyEnforcementDelegator delegator; public PolicyAdministratorPointImpl() { this.policyManager = new PolicyManagerImpl(); this.profileManager = new ProfileManagerImpl(); this.featureManager = new FeatureManagerImpl(); - this.delegator = new PolicyEnforcementDelegatorImpl(); + this.cacheManager = PolicyCacheManagerImpl.getInstance(); + // this.delegator = new PolicyEnforcementDelegatorImpl(); } @Override @@ -63,6 +68,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { // } catch (PolicyDelegationException e) { // throw new PolicyManagementException("Error occurred while delegating policy operation to the devices", e); // } + PolicyCacheManagerImpl.getInstance().addPolicy(resultantPolicy); return resultantPolicy; } @@ -74,42 +80,148 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { // } catch (PolicyDelegationException e) { // throw new PolicyManagementException("Error occurred while delegating policy operation to the devices", e); // } + PolicyCacheManagerImpl.getInstance().updatePolicy(resultantPolicy); return resultantPolicy; } @Override public boolean updatePolicyPriorities(List policies) throws PolicyManagementException { - return policyManager.updatePolicyPriorities(policies); + boolean bool = policyManager.updatePolicyPriorities(policies); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + return bool; + } + + @Override + public void activatePolicy(int policyId) throws PolicyManagementException { + policyManager.activatePolicy(policyId); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + } + + @Override + public void inactivatePolicy(int policyId) throws PolicyManagementException { + policyManager.inactivatePolicy(policyId); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); } @Override public boolean deletePolicy(Policy policy) throws PolicyManagementException { - return policyManager.deletePolicy(policy); + boolean bool = policyManager.deletePolicy(policy); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + return bool; } @Override public boolean deletePolicy(int policyId) throws PolicyManagementException { - return policyManager.deletePolicy(policyId); + boolean bool =policyManager.deletePolicy(policyId); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + return bool; + } + + @Override + public void publishChanges() throws PolicyManagementException { + + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); + taskService.registerTaskType(PolicyManagementConstants.DELEGATION_TASK_TYPE); + + if (log.isDebugEnabled()) { + log.debug("Policy delegations task is started for the tenant id " + tenantId); + } + + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.DELEGATION_TASK_TYPE); + + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + + triggerInfo.setIntervalMillis(0); + triggerInfo.setRepeatCount(1); + + Map properties = new HashMap<>(); + properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); + + String taskName = PolicyManagementConstants.DELEGATION_TASK_NAME + "_" + String.valueOf(tenantId); + + if (!taskManager.isTaskScheduled(taskName)) { + + TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.DELEGATION_TASK_CLAZZ, + properties, triggerInfo); + + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new PolicyManagementException("There is a task already running for policy changes. Please try " + + "to apply " + + "changes after few minutes."); + } + + } catch (TaskException e) { + String msg = "Error occurred while creating the policy delegation task for tenant " + + PrivilegedCarbonContext. + getThreadLocalCarbonContext().getTenantId(); + log.error(msg, e); + throw new PolicyManagementException(msg, e); + } + +// List deviceTypes = policyManager.applyChangesMadeToPolicies(); +// +// if(log.isDebugEnabled()) { +// log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size() ); +// } +// +// if (!deviceTypes.isEmpty()) { +// +// +// DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() +// .getDeviceManagementService(); +// List devices = new ArrayList<>(); +// for (DeviceType deviceType : deviceTypes) { +// try { +// devices.addAll(service.getAllDevices(deviceType.getName())); +// } catch (DeviceManagementException e) { +// throw new PolicyManagementException("Error occurred while taking the devices", e); +// } +// } +// HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); +// List toBeNotified = new ArrayList<>(); +// +// for (Device device : devices) { +// if (deviceIdPolicy.containsKey(device.getId())) { +// toBeNotified.add(device); +// } +// } +// if (!toBeNotified.isEmpty()) { +// +// // ExecutorService executorService = getExecutor(); +// // PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); +//// Thread thread = new Thread(new PolicyEnforcementDelegatorImpl(toBeNotified)); +//// thread.start(); +// } +// } } @Override - public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException { - return policyManager.addPolicyToDevice(deviceIdentifierList, policy); + public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws + PolicyManagementException { + policy = policyManager.addPolicyToDevice(deviceIdentifierList, policy); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + return policy; } @Override public Policy addPolicyToRole(List roleNames, Policy policy) throws PolicyManagementException { - return policyManager.addPolicyToRole(roleNames, policy); + policy = policyManager.addPolicyToRole(roleNames, policy); + PolicyCacheManagerImpl.getInstance().rePopulateCache(); + return policy; } @Override public List getPolicies() throws PolicyManagementException { - return policyManager.getPolicies(); + return PolicyCacheManagerImpl.getInstance().getAllPolicies(); } @Override public Policy getPolicy(int policyId) throws PolicyManagementException { - return policyManager.getPolicy(policyId); + return PolicyCacheManagerImpl.getInstance().getPolicy(policyId); } @Override @@ -185,7 +297,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { try { return profileManager.getProfile(profileId); } catch (ProfileManagementException e) { - String msg = "Error occurred while retriving profile"; + String msg = "Error occurred while retrieving profile"; log.error(msg, e); throw new PolicyManagementException(msg, e); } @@ -220,7 +332,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { @Override public int getPolicyCount() throws PolicyManagementException { - return policyManager.getPolicyCount(); + return PolicyCacheManagerImpl.getInstance().getAllPolicies().size(); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java index f6448508aa..0bd4efe3f5 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java @@ -32,14 +32,56 @@ public class PolicyFilterImpl implements PolicyFilter { private static final Log log = LogFactory.getLog(PolicyFilterImpl.class); + @Override + public List filterActivePolicies(List policies) { + + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterActivePolicies : " + policies.size()); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterActivePolicies : " + policy.getPolicyName()); + } + } + + List temp = new ArrayList(); + for (Policy policy : policies) { + if (policy.isActive()) { + temp.add(policy); + } + } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterActivePolicies :" + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterActivePolicies : " + policy.getPolicyName()); + } + } + + return temp; + } + @Override public List filterRolesBasedPolicies(String roles[], List policies) { + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterRolesBasedPolicies : " + policies.size()); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterRolesBasedPolicies : " + policy.getPolicyName()); + } + log.debug("Roles passed to match."); + for(String role : roles){ + log.debug("Role name passed : " + role); + } + } + List temp = new ArrayList(); for (Policy policy : policies) { List tempRoles = policy.getRoles(); if (tempRoles.isEmpty()) { + + if(log.isDebugEnabled()) { + log.debug("Roles list is empty."); + } temp.add(policy); continue; } @@ -57,12 +99,28 @@ public class PolicyFilterImpl implements PolicyFilter { } } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterRolesBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterRolesBasedPolicies : " + policy.getPolicyName()); + } + } + return temp; } @Override public List filterOwnershipTypeBasedPolicies(String ownershipType, List policies) { + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterOwnershipTypeBasedPolicies : " + policies.size()); + log.debug("Ownership type : " + ownershipType); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterOwnershipTypeBasedPolicies : " + policy.getPolicyName()); + } + } + List temp = new ArrayList(); for (Policy policy : policies) { if (ownershipType.equalsIgnoreCase(policy.getOwnershipType()) || @@ -70,22 +128,56 @@ public class PolicyFilterImpl implements PolicyFilter { temp.add(policy); } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterOwnershipTypeBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterOwnershipTypeBasedPolicies : " + policy.getPolicyName()); + } + } return temp; } @Override public List filterDeviceTypeBasedPolicies(String deviceType, List policies) { + + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterDeviceTypeBasedPolicies : " + policies.size()); + log.debug("Device type : " + deviceType); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterDeviceTypeBasedPolicies : " + policy.getPolicyName()); + } + } + + List temp = new ArrayList(); for (Policy policy : policies) { if (deviceType.equalsIgnoreCase(policy.getProfile().getDeviceType().getName())) { temp.add(policy); } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterDeviceTypeBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterDeviceTypeBasedPolicies : " + policy.getPolicyName()); + } + } + return temp; } @Override public List filterUserBasedPolicies(String username, List policies) { + + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterUserBasedPolicies : " + policies.size()); + log.debug("User name : " + username); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterUserBasedPolicies : " + policy.getPolicyName()); + } + } + List temp = new ArrayList(); for (Policy policy : policies) { @@ -106,6 +198,14 @@ public class PolicyFilterImpl implements PolicyFilter { } } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterUserBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterUserBasedPolicies : " + policy.getPolicyName()); + } + } + return temp; } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java index fde4b6d173..d3591b28e5 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java @@ -27,13 +27,16 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import java.util.ArrayList; import java.util.HashMap; @@ -58,26 +61,36 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { @Override public PIPDevice getDeviceData(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { PIPDevice pipDevice = new PIPDevice(); - org.wso2.carbon.device.mgt.common.Device device; + Device device; DeviceType deviceType = new DeviceType(); deviceType.setName(deviceIdentifier.getType()); - deviceManagementService = getDeviceManagementService(); + DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl(); try { device = deviceManagementService.getDevice(deviceIdentifier); + Thread.currentThread(); + + if (device != null) { /*deviceManagementService.getDeviceType(deviceIdentifier.getType());*/ - pipDevice.setDevice(device); - pipDevice.setRoles(getRoleOfDevice(device)); - pipDevice.setDeviceType(deviceType); - pipDevice.setDeviceIdentifier(deviceIdentifier); - pipDevice.setUserId(device.getEnrolmentInfo().getOwner()); - pipDevice.setOwnershipType(device.getEnrolmentInfo().getOwnership().toString()); - - // TODO : Find a way to retrieve the timestamp and location (lat, long) of the device - // pipDevice.setLongitude(); - // pipDevice.setAltitude(); - // pipDevice.setTimestamp(); + pipDevice.setDevice(device); + pipDevice.setRoles(getRoleOfDevice(device)); + pipDevice.setDeviceType(deviceType); + pipDevice.setDeviceIdentifier(deviceIdentifier); + pipDevice.setUserId(device.getEnrolmentInfo().getOwner()); + pipDevice.setOwnershipType(device.getEnrolmentInfo().getOwnership().toString()); + + // TODO : Find a way to retrieve the timestamp and location (lat, long) of the device + // pipDevice.setLongitude(); + // pipDevice.setAltitude(); + // pipDevice.setTimestamp(); + } else { + // Remove this + for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { + log.debug("StackTraceElement : " + ste); + } + throw new PolicyManagementException("Device details cannot be null."); + } } catch (DeviceManagementException e) { String msg = "Error occurred when retrieving the data related to device from the database."; log.error(msg, e); @@ -93,6 +106,16 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { List policies = policyManager.getPoliciesOfDeviceType(pipDevice.getDeviceType().getName()); PolicyFilter policyFilter = new PolicyFilterImpl(); + if (log.isDebugEnabled()) { + log.debug("No of policies for the device type : " + pipDevice.getDeviceType().getName() + " : " + + policies.size()); + for (Policy policy : policies) { + log.debug("Names of policy for above device type : " + policy.getPolicyName()); + } + } + + policies = policyFilter.filterActivePolicies(policies); + if (pipDevice.getDeviceType() != null) { policies = policyFilter.filterDeviceTypeBasedPolicies(pipDevice.getDeviceType().getName(), policies); } @@ -102,10 +125,18 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { if (pipDevice.getRoles() != null) { policies = policyFilter.filterRolesBasedPolicies(pipDevice.getRoles(), policies); } - if(pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { + if (pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies); } + if (log.isDebugEnabled()) { + log.debug("No of policies selected for the device type : " + pipDevice.getDeviceType().getName() + " : " + + policies.size()); + for (Policy policy : policies) { + log.debug("Names of selected policy for above device type : " + policy.getPolicyName()); + } + } + return policies; } @@ -117,12 +148,14 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { private String[] getRoleOfDevice(Device device) throws PolicyManagementException { try { - return CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner()); + UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm(); + if (userRealm != null) { + return userRealm.getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner()); + } else { + return null; + } } catch (UserStoreException e) { - String msg = "Error occurred when retrieving roles related to user name."; - log.error(msg, e); - throw new PolicyManagementException(msg, e); + throw new PolicyManagementException("Error occurred when retrieving roles related to user name.", e); } } @@ -139,12 +172,11 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { } } } - return finalPolicies; } private DeviceManagementProviderService getDeviceManagementService() { - return PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + return new DeviceManagementProviderServiceImpl(); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java index f0b98fa6f6..1b6f10c162 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -21,6 +21,8 @@ package org.wso2.carbon.policy.mgt.core.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint; @@ -31,6 +33,8 @@ import org.wso2.carbon.policy.mgt.core.config.PolicyConfigurationManager; import org.wso2.carbon.policy.mgt.core.config.PolicyManagementConfig; import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; +import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl; import org.wso2.carbon.user.core.service.RealmService; /** @@ -82,6 +86,13 @@ public class PolicyManagementServiceComponent { componentContext.getBundleContext().registerService( PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null); + PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getPolicyConfiguration(); + if(policyConfiguration.getMonitoringEnable()) { + TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl(); + taskScheduleService.startTask(policyConfiguration.getMonitoringFrequency()); + } + } catch (Throwable t) { log.error("Error occurred while initializing the Policy management core.", t); } @@ -160,7 +171,7 @@ public class PolicyManagementServiceComponent { protected void setPolicyMonitoringService(PolicyMonitoringService policyMonitoringService) { if (log.isDebugEnabled()) { - log.debug("Setting Policy Monitoring Service"); + log.debug("Setting Policy Monitoring Service for " + policyMonitoringService.getType()); } // TODO: FIX THE device type by taking from properties PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(policyMonitoringService.getType(), @@ -169,7 +180,7 @@ public class PolicyManagementServiceComponent { protected void unsetPolicyMonitoringService(PolicyMonitoringService policyMonitoringService) { if (log.isDebugEnabled()) { - log.debug("Removing the Policy Monitoring Service"); + log.debug("Removing the Policy Monitoring Service for " + policyMonitoringService.getType()); } // TODO: FIX THE device type by taking from properties PolicyManagementDataHolder.getInstance().unsetPolicyMonitoringService(policyMonitoringService.getType()); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java index 9da602f261..883d49237d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.mgt; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; @@ -39,4 +40,6 @@ public interface MonitoringManager { void addMonitoringOperation(List devices) throws PolicyComplianceException; + List getDeviceTypes() throws PolicyComplianceException; + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java index edc02bb973..6ac0e6b50b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java @@ -19,10 +19,12 @@ package org.wso2.carbon.policy.mgt.core.mgt; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.ProfileFeature; +import java.util.HashMap; import java.util.List; public interface PolicyManager { @@ -37,6 +39,10 @@ public interface PolicyManager { boolean deletePolicy(int policyId) throws PolicyManagementException; + void activatePolicy(int policyId) throws PolicyManagementException; + + void inactivatePolicy(int policyId) throws PolicyManagementException; + Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException; @@ -63,6 +69,8 @@ public interface PolicyManager { void addAppliedPolicyFeaturesToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException; + List applyChangesMadeToPolicies() throws PolicyManagementException; + void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException; boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; @@ -72,4 +80,6 @@ public interface PolicyManager { int getPolicyCount() throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; + + HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagementException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 09425753fc..6b52b04e7a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -26,8 +26,13 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfigRepository; +import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; @@ -54,18 +59,24 @@ import java.util.Map; public class MonitoringManagerImpl implements MonitoringManager { private PolicyDAO policyDAO; - private DeviceDAO deviceDAO; +// private DeviceDAO deviceDAO; + private DeviceTypeDAO deviceTypeDAO; private MonitoringDAO monitoringDAO; private ComplianceDecisionPoint complianceDecisionPoint; + private PolicyConfiguration policyConfiguration; private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class); private static final String OPERATION_MONITOR = "MONITOR"; public MonitoringManagerImpl() { this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); - this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); +// this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); + this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.monitoringDAO = PolicyManagementDAOFactory.getMonitoringDAO(); this.complianceDecisionPoint = new ComplianceDecisionPointImpl(); + this.policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getPolicyConfiguration(); + } @Override @@ -77,8 +88,7 @@ public class MonitoringManagerImpl implements MonitoringManager { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); PolicyManager manager = new PolicyManagerImpl(); Device device = service.getDevice(deviceIdentifier); - Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); //policyDAO.getAppliedPolicy(device - // .getId()); + Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); if (policy != null) { PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance(). getPolicyMonitoringService(deviceIdentifier.getType()); @@ -106,14 +116,19 @@ public class MonitoringManagerImpl implements MonitoringManager { //This was added because update query below that did not return the update table primary key. if (complianceFeatures != null && !complianceFeatures.isEmpty()) { - PolicyManagementDAOFactory.beginTransaction(); - monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); - if (log.isDebugEnabled()) { - log.debug("Compliance status primary key " + complianceData.getId()); + try { + PolicyManagementDAOFactory.beginTransaction(); + monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); + if (log.isDebugEnabled()) { + log.debug("Compliance status primary key " + complianceData.getId()); + } + monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), + complianceFeatures); + + PolicyManagementDAOFactory.commitTransaction(); + } finally { + PolicyManagementDAOFactory.closeConnection(); } -// complianceData.setId(cmf.getId()); - monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures); - PolicyManagementDAOFactory.commitTransaction(); complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData); List profileFeatures = policy.getProfile().getProfileFeaturesList(); for (ComplianceFeature compFeature : complianceFeatures) { @@ -124,11 +139,14 @@ public class MonitoringManagerImpl implements MonitoringManager { } } } else { - PolicyManagementDAOFactory.beginTransaction(); - monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); - //complianceData.setId(cmf.getId()); - monitoringDAO.deleteNoneComplianceData(complianceData.getId()); - PolicyManagementDAOFactory.commitTransaction(); + try { + PolicyManagementDAOFactory.beginTransaction(); + monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); + monitoringDAO.deleteNoneComplianceData(complianceData.getId()); + PolicyManagementDAOFactory.commitTransaction(); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } } } else { if (log.isDebugEnabled()) { @@ -147,8 +165,6 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Unable to add the none compliance features to database for device " + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); - } finally { - PolicyManagementDAOFactory.closeConnection(); } return complianceFeatures; } @@ -158,7 +174,6 @@ public class MonitoringManagerImpl implements MonitoringManager { try { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); - //deviceDAO.getDevice(deviceIdentifier, tenantId); PolicyManagementDAOFactory.openConnection(); ComplianceData complianceData = monitoringDAO.getCompliance(device.getId()); if (complianceData == null || !complianceData.isStatus()) { @@ -210,28 +225,42 @@ public class MonitoringManagerImpl implements MonitoringManager { @Override public void addMonitoringOperation(List devices) throws PolicyComplianceException { - try { - ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl(); - //int tenantId = PolicyManagerUtil.getTenantId(); - Map deviceIds = new HashMap<>(); + ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl(); - for (Device device : devices) { - deviceIds.put(device.getId(), device); - } + //int tenantId = PolicyManagerUtil.getTenantId(); + Map deviceIds = new HashMap<>(); + List complianceDatas; + HashMap devicePolicyIdMap; - List deviceIDs = new ArrayList<>(deviceIds.keySet()); - List complianceDatas = monitoringDAO.getCompliance(deviceIDs); - HashMap devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs); + for (Device device : devices) { + deviceIds.put(device.getId(), device); + } - Map deviceIdsToAddOperation = new HashMap<>(); - Map deviceIdsWithExistingOperation = new HashMap<>(); - Map inactiveDeviceIds = new HashMap<>(); - Map firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); + List deviceIDs = new ArrayList<>(deviceIds.keySet()); + try { + PolicyManagementDAOFactory.openConnection(); + complianceDatas = monitoringDAO.getCompliance(deviceIDs); + devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs); + } catch (SQLException e) { + throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); + } catch (MonitoringDAOException e) { + throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); + } catch (PolicyManagerDAOException e) { + throw new PolicyComplianceException("SQL error occurred while getting policy details.", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } - Map tempMap = new HashMap<>(); + Map deviceIdsToAddOperation = new HashMap<>(); + Map deviceIdsWithExistingOperation = new HashMap<>(); + Map inactiveDeviceIds = new HashMap<>(); + Map deviceToMarkUnreachable = new HashMap<>(); + Map firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); + Map tempMap = new HashMap<>(); + try { if (complianceDatas != null || !complianceDatas.isEmpty()) { for (ComplianceData complianceData : complianceDatas) { @@ -243,8 +272,12 @@ public class MonitoringManagerImpl implements MonitoringManager { } else { deviceIdsWithExistingOperation.put(complianceData.getDeviceId(), deviceIds.get(complianceData.getDeviceId())); + if (complianceData.getAttempts() >= policyConfiguration.getMinRetriesToMarkUnreachable()) { + deviceToMarkUnreachable.put(complianceData.getDeviceId(), + deviceIds.get(complianceData.getDeviceId())); + } } - if (complianceData.getAttempts() >= 20) { + if (complianceData.getAttempts() >= policyConfiguration.getMinRetriesToMarkInactive()) { inactiveDeviceIds.put(complianceData.getDeviceId(), deviceIds.get(complianceData.getDeviceId())); } @@ -252,7 +285,7 @@ public class MonitoringManagerImpl implements MonitoringManager { } for (Device device : devices) { - if (!tempMap.containsKey(device.getId())) { + if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) { deviceIdsToAddOperation.put(device.getId(), device); firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId())); } @@ -268,30 +301,55 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyManagementDAOFactory.beginTransaction(); if (!deviceIdsToAddOperation.isEmpty()) { - this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values())); monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); } if (!deviceIdsWithExistingOperation.isEmpty()) { monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsWithExistingOperation.keySet()), false); - //TODO: Add attempts. This has to be fixed in the get pending operation tables too. This will be -// decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices( -// new ArrayList<>(deviceIdsWithExistingOperation.values()))); } - PolicyManagementDAOFactory.commitTransaction(); + } catch (MonitoringDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Error occurred from monitoring dao.", e); - } catch (OperationManagementException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Error occurred reading the applied policies to devices.", e); } finally { PolicyManagementDAOFactory.closeConnection(); } + + if (!deviceIdsToAddOperation.isEmpty()) { + try { + this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values())); + } catch (OperationManagementException e) { + throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e); + } + } + + // TODO : This should be uncommented, this is to mark the device as unreachable, But given the current implementation + // we are not able to do so. + +// if(!deviceToMarkUnreachable.isEmpty()) { +// decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices( +// new ArrayList<>(deviceToMarkUnreachable.values()))); +// } + + } + + @Override + public List getDeviceTypes() throws PolicyComplianceException { + + List deviceTypes = new ArrayList<>(); + try { + DeviceManagementDAOFactory.openConnection(); + deviceTypes = deviceTypeDAO.getDeviceTypes(); + } catch (Exception e) { + log.error("Error occurred while getting the device types.", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return deviceTypes; } private void addMonitoringOperationsToDatabase(List devices) @@ -305,8 +363,7 @@ public class MonitoringManagerImpl implements MonitoringManager { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); service.addOperation(monitoringOperation, deviceIdentifiers); -// PolicyManagementDataHolder.getInstance().getDeviceManagementService(). -// addOperation(monitoringOperation, deviceIdentifiers); + } private List getDeviceIdentifiersFromDevices(List devices) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 71daa41ec8..6412c80db7 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -20,35 +20,36 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; +import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import java.sql.SQLException; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.List; +import java.util.*; public class PolicyManagerImpl implements PolicyManager { private PolicyDAO policyDAO; private ProfileDAO profileDAO; private FeatureDAO featureDAO; - private DeviceDAO deviceDAO; - // private DeviceTypeDAO deviceTypeDAO; private ProfileManager profileManager; + private PolicyCacheManager policyCacheManager; + private DeviceDAO deviceDAO; private static Log log = LogFactory.getLog(PolicyManagerImpl.class); public PolicyManagerImpl() { @@ -56,7 +57,6 @@ public class PolicyManagerImpl implements PolicyManager { this.profileDAO = PolicyManagementDAOFactory.getProfileDAO(); this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); -// this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.profileManager = new ProfileManagerImpl(); } @@ -72,7 +72,6 @@ public class PolicyManagerImpl implements PolicyManager { profile.setCreatedDate(currentTimestamp); profile.setUpdatedDate(currentTimestamp); - profileDAO.addProfile(profile); featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); } @@ -110,17 +109,6 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); } -// if (policy.getEndDate() != null & policy.getStartDate() != null) { -// policyDAO.addDatesToPolicy(policy.getStartDate(), policy.getEndDate(), policy); -// } -// -// if (policy.getStartTime() != 0 & policy.getEndTime() != 0) { -// policyDAO.addTimesToPolicy(policy.getStartTime(), policy.getEndTime(), policy); -// } -// -// if (policy.getLatitude() != null && policy.getLongitude() != null) { -// policyDAO.addLocationToPolicy(policy.getLatitude(), policy.getLongitude(), policy); -// } PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { @@ -147,7 +135,13 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.beginTransaction(); - policy = policyDAO.updatePolicy(policy); + // This will keep track of the policies updated. + policyDAO.recordUpdatedPolicy(policy); + + policyDAO.updatePolicy(policy); + profileDAO.updateProfile(policy.getProfile()); + featureDAO.updateProfileFeatures(policy.getProfile().getProfileFeaturesList(), policy.getProfile() + .getProfileId()); policyDAO.deleteAllPolicyRelatedConfigs(policy.getId()); if (policy.getUsers() != null) { @@ -177,23 +171,20 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); } -// if (policy.getEndDate() != null & policy.getStartDate() != null) { -// policyDAO.addDatesToPolicy(policy.getStartDate(), policy.getEndDate(), policy); -// } -// -// if (policy.getStartTime() != 0 & policy.getEndTime() != 0) { -// policyDAO.addTimesToPolicy(policy.getStartTime(), policy.getEndTime(), policy); -// } -// -// if (policy.getLatitude() != null && policy.getLongitude() != null) { -// policyDAO.addLocationToPolicy(policy.getLatitude(), policy.getLongitude(), policy); -// } - PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while updating the policy (" + policy.getId() + " - " + policy.getPolicyName() + ")", e); + } catch (ProfileManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while updating the profile (" + + policy.getProfile().getProfileName() + ")", e); + } catch (FeatureManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while updating the profile features (" + + policy.getProfile().getProfileName() + ")", e); + } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -204,8 +195,21 @@ public class PolicyManagerImpl implements PolicyManager { public boolean updatePolicyPriorities(List policies) throws PolicyManagementException { boolean bool; try { +// List existingPolicies = this.getPolicies(); + List existingPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); PolicyManagementDAOFactory.beginTransaction(); bool = policyDAO.updatePolicyPriorities(policies); + + // This logic is added because ui sends only policy id and priority to update priorities. + + for (Policy policy : policies) { + for (Policy exPolicy : existingPolicies) { + if (policy.getId() == exPolicy.getId()) { + policy.setProfile(exPolicy.getProfile()); + } + } + } + policyDAO.recordUpdatedPolicies(policies); PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); @@ -245,12 +249,13 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean deletePolicy(int policyId) throws PolicyManagementException { + boolean bool; try { PolicyManagementDAOFactory.beginTransaction(); Policy policy = policyDAO.getPolicy(policyId); policyDAO.deleteAllPolicyRelatedConfigs(policyId); - policyDAO.deletePolicy(policyId); + bool = policyDAO.deletePolicy(policyId); if (log.isDebugEnabled()) { log.debug("Profile ID: " + policy.getProfileId()); @@ -260,7 +265,7 @@ public class PolicyManagerImpl implements PolicyManager { profileDAO.deleteProfile(policy.getProfileId()); PolicyManagementDAOFactory.commitTransaction(); - return true; + return bool; } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while deleting the policy (" + policyId + ")", e); @@ -278,14 +283,52 @@ public class PolicyManagerImpl implements PolicyManager { } @Override - public Policy addPolicyToDevice(List deviceIds, Policy policy) throws PolicyManagementException { + public void activatePolicy(int policyId) throws PolicyManagementException { + try { + Policy policy = this.getPolicy(policyId); + PolicyManagementDAOFactory.beginTransaction(); + policyDAO.activatePolicy(policyId); + policyDAO.recordUpdatedPolicy(policy); + PolicyManagementDAOFactory.commitTransaction(); + } catch (PolicyManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while activating the policy. (Id : " + policyId + ")" + + "", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + } + + @Override + public void inactivatePolicy(int policyId) throws PolicyManagementException { + try { + Policy policy = this.getPolicy(policyId); + PolicyManagementDAOFactory.beginTransaction(); + policyDAO.inactivatePolicy(policyId); + policyDAO.recordUpdatedPolicy(policy); + PolicyManagementDAOFactory.commitTransaction(); + } catch (PolicyManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while inactivating the policy. (Id : " + policyId + + ")" + + "", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + } + + @Override + public Policy addPolicyToDevice(List deviceIdentifierList, + Policy policy) throws PolicyManagementException { + List deviceList = new ArrayList<>(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - for (DeviceIdentifier deviceIdentifier : deviceIds) { + for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) { try { - deviceList.add(service.getDevice(deviceIdentifier)); + Device device = service.getDevice(deviceIdentifier); + deviceList.add(device); } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while adding the policy to device list", e); + throw new PolicyManagementException("Error occurred while retrieving device information", e); } } try { @@ -293,6 +336,7 @@ public class PolicyManagerImpl implements PolicyManager { if (policy.getId() == 0) { policyDAO.addPolicy(policy); } + policy = policyDAO.addPolicyToDevice(deviceList, policy); PolicyManagementDAOFactory.commitTransaction(); @@ -391,17 +435,12 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicyByProfileID(profileId); - deviceList = getPolicyAppliedDevicesIds(policy.getId()); - roleNames = policyDAO.getPolicyAppliedRoles(policy.getId()); -// policyDAO.getDatesOfPolicy(policy); -// policyDAO.getTimesOfPolicy(policy); -// policyDAO.getLocationsOfPolicy(policy); + roleNames = policyDAO.getPolicyAppliedRoles(policy.getId()); profile = profileDAO.getProfiles(profileId); - policy.setProfile(profile); policy.setRoles(roleNames); - policy.setDevices(deviceList); + } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to profile ID (" + @@ -414,6 +453,10 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } + + // This is due to connection close in following method too. + deviceList = getPolicyAppliedDevicesIds(policy.getId()); + policy.setDevices(deviceList); return policy; } @@ -427,17 +470,13 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicy(policyId); - deviceList = getPolicyAppliedDevicesIds(policyId); - roleNames = policyDAO.getPolicyAppliedRoles(policyId); -// policyDAO.getDatesOfPolicy(policy); -// policyDAO.getTimesOfPolicy(policy); -// policyDAO.getLocationsOfPolicy(policy); + roleNames = policyDAO.getPolicyAppliedRoles(policyId); Profile profile = profileDAO.getProfiles(policy.getProfileId()); policy.setProfile(profile); policy.setRoles(roleNames); - policy.setDevices(deviceList); + } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" + @@ -450,11 +489,16 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } + + // This is done because connection close in below method too. + deviceList = this.getPolicyAppliedDevicesIds(policyId); + policy.setDevices(deviceList); return policy; } @Override public List getPolicies() throws PolicyManagementException { + List policyList; List profileList; try { @@ -465,7 +509,6 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policyList = policyDAO.getAllPolicies(); -// List profileList = profileDAO.getAllProfiles(); for (Policy policy : policyList) { for (Profile profile : profileList) { @@ -473,13 +516,9 @@ public class PolicyManagerImpl implements PolicyManager { policy.setProfile(profile); } } - policy.setDevices(getPolicyAppliedDevicesIds(policy.getId())); policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId())); policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId())); policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId())); -// policyDAO.getDatesOfPolicy(policy); -// policyDAO.getTimesOfPolicy(policy); -// policyDAO.getLocationsOfPolicy(policy); } Collections.sort(policyList); } catch (PolicyManagerDAOException e) { @@ -489,6 +528,13 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } + + // Following is done because connection close has been implemented in every method. + + for (Policy policy : policyList) { + policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId())); + } + return policyList; } @@ -498,9 +544,11 @@ public class PolicyManagerImpl implements PolicyManager { List policyIdList; List policies = new ArrayList<>(); try { - PolicyManagementDAOFactory.openConnection(); + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); + + PolicyManagementDAOFactory.openConnection(); policyIdList = policyDAO.getPolicyIdsOfDevice(device); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policies for device identifier (" + @@ -514,7 +562,8 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.closeConnection(); } - List tempPolicyList = this.getPolicies(); +// List tempPolicyList = this.getPolicies(); + List tempPolicyList = PolicyCacheManagerImpl.getInstance().getAllPolicies(); for (Policy policy : tempPolicyList) { for (Integer i : policyIdList) { @@ -531,22 +580,29 @@ public class PolicyManagerImpl implements PolicyManager { @Override public List getPoliciesOfDeviceType(String deviceTypeName) throws PolicyManagementException { List policies = new ArrayList<>(); - try { - List profileList = profileManager.getProfilesOfDeviceType(deviceTypeName); - List allPolicies = this.getPolicies(); - - for (Profile profile : profileList) { - for (Policy policy : allPolicies) { - if (policy.getProfileId() == profile.getProfileId()) { - policy.setProfile(profile); - policies.add(policy); - } - } +// try { + // List profileList = profileManager.getProfilesOfDeviceType(deviceTypeName); +// List allPolicies = this.getPolicies(); + List allPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); + + for (Policy policy : allPolicies) { + if (policy.getProfile().getDeviceType().getName().equalsIgnoreCase(deviceTypeName)) { + policies.add(policy); } - Collections.sort(policies); - } catch (ProfileManagementException e) { - throw new PolicyManagementException("Error occurred while getting all the profile features.", e); } + +// for (Profile profile : profileList) { +// for (Policy policy : allPolicies) { +// if (policy.getProfileId() == profile.getProfileId()) { +// policy.setProfile(profile); +// policies.add(policy); +// } +// } +// } + Collections.sort(policies); +// } catch (ProfileManagementException e) { +// throw new PolicyManagementException("Error occurred while getting all the profile features.", e); +// } return policies; } @@ -568,7 +624,8 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.closeConnection(); } - List tempPolicyList = this.getPolicies(); +// List tempPolicyList = this.getPolicies(); + List tempPolicyList = PolicyCacheManagerImpl.getInstance().getAllPolicies(); for (Policy policy : tempPolicyList) { for (Integer i : policyIdList) { @@ -597,7 +654,8 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } - List tempPolicyList = this.getPolicies(); +// List tempPolicyList = this.getPolicies(); + List tempPolicyList = PolicyCacheManagerImpl.getInstance().getAllPolicies(); for (Policy policy : tempPolicyList) { for (Integer i : policyIdList) { @@ -612,17 +670,47 @@ public class PolicyManagerImpl implements PolicyManager { @Override public List getPolicyAppliedDevicesIds(int policyId) throws PolicyManagementException { + List deviceList = new ArrayList<>(); List deviceIds; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + List allDevices = service.getAllDevices(); + PolicyManagementDAOFactory.openConnection(); + + //int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); + + + HashMap allDeviceMap = new HashMap<>(); + + if (!allDevices.isEmpty()) { + allDeviceMap = PolicyManagerUtil.covertDeviceListToMap(allDevices); + } + + for (int deviceId : deviceIds) { + + if (allDeviceMap.containsKey(deviceId)) { + if (log.isDebugEnabled()) { + log.debug("Policy Applied device ids .............: " + deviceId + " - Policy Id " + policyId); + } + deviceList.add(allDeviceMap.get(deviceId)); + } + + //TODO FIX ME -- This is wrong, Device id is not device identifier, so converting is wrong. + + //deviceList.add(deviceDAO.getDevice(new DeviceIdentifier(Integer.toString(deviceId), ""), tenantId)); + } } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the device ids related to policy id (" + policyId + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + + policyId + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -654,11 +742,11 @@ public class PolicyManagerImpl implements PolicyManager { deviceId = device.getId(); PolicyManagementDAOFactory.beginTransaction(); - boolean exist = policyDAO.checkPolicyAvailable(deviceId); + boolean exist = policyDAO.checkPolicyAvailable(deviceId, device.getEnrolmentInfo().getId()); if (exist) { - policyDAO.updateEffectivePolicyToDevice(deviceId, policy); + policyDAO.updateEffectivePolicyToDevice(deviceId, device.getEnrolmentInfo().getId(), policy); } else { - policyDAO.addEffectivePolicyToDevice(deviceId, policy); + policyDAO.addEffectivePolicyToDevice(deviceId, device.getEnrolmentInfo().getId(), policy); } PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { @@ -673,6 +761,48 @@ public class PolicyManagerImpl implements PolicyManager { } } + @Override + public List applyChangesMadeToPolicies() throws PolicyManagementException { + + List changedDeviceTypes = new ArrayList<>(); + try { + //HashMap map = policyDAO.getUpdatedPolicyIdandDeviceTypeId(); + List updatedPolicies = new ArrayList<>(); +// List activePolicies = new ArrayList<>(); +// List inactivePolicies = new ArrayList<>(); + List updatedPolicyIds = new ArrayList<>(); + +// List allPolicies = this.getPolicies(); + List allPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); + + for (Policy policy : allPolicies) { + if (policy.isUpdated()) { + updatedPolicies.add(policy); + updatedPolicyIds.add(policy.getId()); + if (!changedDeviceTypes.contains(policy.getProfile().getDeviceType())) { + changedDeviceTypes.add(policy.getProfile().getDeviceType()); + } + } +// if (policy.isActive()) { +// activePolicies.add(policy); +// } else { +// inactivePolicies.add(policy); +// } + } + PolicyManagementDAOFactory.beginTransaction(); + policyDAO.markPoliciesAsUpdated(updatedPolicyIds); + policyDAO.removeRecordsAboutUpdatedPolicies(); + PolicyManagementDAOFactory.commitTransaction(); + } catch (PolicyManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while applying the changes to policy operations.", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + return changedDeviceTypes; + } + + @Override public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException { @@ -682,17 +812,15 @@ public class PolicyManagerImpl implements PolicyManager { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); deviceId = device.getId(); - // boolean exist = policyDAO.checkPolicyAvailable(deviceId); - PolicyManagementDAOFactory.beginTransaction(); - Policy policySaved = policyDAO.getAppliedPolicy(deviceId); + Policy policySaved = policyDAO.getAppliedPolicy(deviceId, device.getEnrolmentInfo().getId()); if (policySaved != null && policySaved.getId() != 0) { if (policy.getId() != policySaved.getId()) { - policyDAO.updateEffectivePolicyToDevice(deviceId, policy); + policyDAO.updateEffectivePolicyToDevice(deviceId, device.getEnrolmentInfo().getId(), policy); } } else { - policyDAO.addEffectivePolicyToDevice(deviceId, policy); + policyDAO.addEffectivePolicyToDevice(deviceId, device.getEnrolmentInfo().getId(), policy); } PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { @@ -713,10 +841,10 @@ public class PolicyManagerImpl implements PolicyManager { boolean exist; try { - PolicyManagementDAOFactory.openConnection(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); - exist = policyDAO.checkPolicyAvailable(device.getId()); + PolicyManagementDAOFactory.openConnection(); + exist = policyDAO.checkPolicyAvailable(device.getId(), device.getEnrolmentInfo().getId()); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while checking whether device has a policy " + "to apply.", e); @@ -734,10 +862,11 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean setPolicyApplied(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { try { - PolicyManagementDAOFactory.openConnection(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); - policyDAO.setPolicyApplied(device.getId()); + + PolicyManagementDAOFactory.openConnection(); + policyDAO.setPolicyApplied(device.getId(), device.getEnrolmentInfo().getId()); return true; } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while setting the policy has applied to device (" + @@ -777,7 +906,7 @@ public class PolicyManagerImpl implements PolicyManager { Device device = service.getDevice(deviceIdentifier); //int policyId = policyDAO.getAppliedPolicyId(device.getId()); PolicyManagementDAOFactory.openConnection(); - policy = policyDAO.getAppliedPolicy(device.getId()); + policy = policyDAO.getAppliedPolicy(device.getId(), device.getEnrolmentInfo().getId()); } catch (DeviceManagementException e) { throw new PolicyManagementException("Error occurred while getting device id.", e); } catch (PolicyManagerDAOException e) { @@ -790,4 +919,18 @@ public class PolicyManagerImpl implements PolicyManager { return policy; } + @Override + public HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagementException { + try { + PolicyManagementDAOFactory.openConnection(); + return policyDAO.getAppliedPolicyIdsDeviceIds(); + } catch (PolicyManagerDAOException e) { + throw new PolicyManagementException("Error occurred while reading the policy applied database.", e); + } catch (SQLException e) { + throw new PolicyManagementException("Error occurred while reading the policy applied database.", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 2b0eacb1a2..6c7cfcdb69 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -42,13 +42,13 @@ public class ProfileManagerImpl implements ProfileManager { private static Log log = LogFactory.getLog(ProfileManagerImpl.class); private ProfileDAO profileDAO; private FeatureDAO featureDAO; - private DeviceDAO deviceDAO; +// private DeviceDAO deviceDAO; private DeviceTypeDAO deviceTypeDAO; public ProfileManagerImpl() { profileDAO = PolicyManagementDAOFactory.getProfileDAO(); featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); - deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); +// deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); } @@ -91,7 +91,7 @@ public class ProfileManagerImpl implements ProfileManager { try { PolicyManagementDAOFactory.beginTransaction(); - profile = profileDAO.updateProfile(profile); + profileDAO.updateProfile(profile); featureDAO.updateProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); PolicyManagementDAOFactory.commitTransaction(); } catch (ProfileManagerDAOException e) { @@ -150,7 +150,6 @@ public class ProfileManagerImpl implements ProfileManager { profile = profileDAO.getProfiles(profileId); featureList = featureDAO.getFeaturesForProfile(profileId); profile.setProfileFeaturesList(featureList); - profile.setDeviceType(deviceType); } catch (ProfileManagerDAOException e) { throw new ProfileManagementException("Error occurred while getting profile id (" + profileId + ")", e); } catch (FeatureManagerDAOException e) { @@ -165,15 +164,17 @@ public class ProfileManagerImpl implements ProfileManager { try { DeviceManagementDAOFactory.openConnection(); deviceType = deviceTypeDAO.getDeviceType(profile.getDeviceType().getId()); - profile.setDeviceType(deviceType); - } catch (SQLException e) { - throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } catch (DeviceManagementDAOException e) { - throw new ProfileManagementException("Error occurred while getting device type related profile id (" + + throw new ProfileManagementException("Error occurred while getting features related profile id (" + + profileId + ")", e); + } catch (SQLException e) { + throw new ProfileManagementException("SQL exception occurred while getting features related profile id (" + profileId + ")", e); } finally { DeviceManagementDAOFactory.closeConnection(); } + + profile.setDeviceType(deviceType); return profile; } @@ -181,20 +182,23 @@ public class ProfileManagerImpl implements ProfileManager { public List getAllProfiles() throws ProfileManagementException { List profileList; List deviceTypes; + try { DeviceManagementDAOFactory.openConnection(); deviceTypes = deviceTypeDAO.getDeviceTypes(); } catch (SQLException e) { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } catch (DeviceManagementDAOException e) { - throw new ProfileManagementException("Error occurred while getting device types related to profiles", e); + throw new ProfileManagementException("Error occurred while retrieving device type information", e); } finally { DeviceManagementDAOFactory.closeConnection(); } + try { PolicyManagementDAOFactory.openConnection(); profileList = profileDAO.getAllProfiles(); List featureList = featureDAO.getAllProfileFeatures(); + for (Profile profile : profileList) { List list = new ArrayList(); @@ -219,6 +223,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); + // DeviceManagementDAOFactory.closeConnection(); } return profileList; } @@ -228,18 +233,21 @@ public class ProfileManagerImpl implements ProfileManager { List profileList; List featureList; DeviceType deviceType; + try { DeviceManagementDAOFactory.openConnection(); deviceType = deviceTypeDAO.getDeviceType(deviceTypeName); + } catch (DeviceManagementDAOException e) { + throw new ProfileManagementException("Error occurred while retrieving device type information", e); } catch (SQLException e) { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); - } catch (DeviceManagementDAOException e) { - throw new ProfileManagementException("Error occurred while getting device types", e); } finally { DeviceManagementDAOFactory.closeConnection(); } + try { PolicyManagementDAOFactory.openConnection(); + profileList = profileDAO.getProfilesOfDeviceType(deviceType); featureList = featureDAO.getAllProfileFeatures(); @@ -260,6 +268,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); + } return profileList; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index ac4563bd8a..cff114bf40 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -23,11 +23,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; @@ -62,48 +64,66 @@ public class MonitoringTask implements Task { log.debug("Monitoring task started to run."); } + MonitoringManager monitoringManager = new MonitoringManagerImpl(); + + List deviceTypes = new ArrayList<>(); try { - List deviceTypes = deviceTypeDAO.getDeviceTypes(); - DeviceManagementProviderService deviceManagementProviderService = - PolicyManagementDataHolder.getInstance().getDeviceManagementService(); - MonitoringManager monitoringManager = new MonitoringManagerImpl(); - - for (DeviceType deviceType : deviceTypes) { - PolicyMonitoringService monitoringService = - PolicyManagementDataHolder.getInstance().getPolicyMonitoringService(deviceType.getName()); - List devices = deviceManagementProviderService.getAllDevices(deviceType.getName()); - if (monitoringService != null && !devices.isEmpty()) { - monitoringManager.addMonitoringOperation(devices); - - List notifiableDevices = new ArrayList<>(); - - if (log.isDebugEnabled()) { - log.debug("Removing inactive and blocked devices from the list for the device type : " + - deviceType); + deviceTypes = monitoringManager.getDeviceTypes(); + } catch (PolicyComplianceException e) { + log.error("Error occurred while getting the device types."); + } + + if (!deviceTypes.isEmpty()) { + try { + + + + DeviceManagementProviderService deviceManagementProviderService = + PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + + for (DeviceType deviceType : deviceTypes) { + + if(log.isDebugEnabled()){ + log.debug("Running task for device type : " + deviceType.getName() ); } - for (Device device : devices) { - if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.INACTIVE) || - device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.BLOCKED)) { - continue; - } else { - notifiableDevices.add(device); + + PolicyMonitoringService monitoringService = + PolicyManagementDataHolder.getInstance().getPolicyMonitoringService(deviceType.getName()); + List devices = deviceManagementProviderService.getAllDevices(deviceType.getName()); + if (monitoringService != null && !devices.isEmpty()) { + monitoringManager.addMonitoringOperation(devices); + + List notifiableDevices = new ArrayList<>(); + + if (log.isDebugEnabled()) { + log.debug("Removing inactive and blocked devices from the list for the device type : " + + deviceType.getName()); } - } - if (log.isDebugEnabled()) { - log.debug("Following devices selected to send the notification for " + deviceType); - for (Device device : notifiableDevices) { - log.debug(device.getDeviceIdentifier()); + for (Device device : devices) { + if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.INACTIVE) || + device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.BLOCKED)) { + continue; + } else { + notifiableDevices.add(device); + } } + if (log.isDebugEnabled()) { + log.debug("Following devices selected to send the notification for " + deviceType.getName()); + for (Device device : notifiableDevices) { + log.debug(device.getDeviceIdentifier()); + } + } + monitoringService.notifyDevices(notifiableDevices); } - monitoringService.notifyDevices(notifiableDevices); } + if (log.isDebugEnabled()) { + log.debug("Monitoring task running completed."); + } + } catch (Exception e) { + log.error("Error occurred while trying to run a task.", e); } - if (log.isDebugEnabled()) { - log.debug("Monitoring task running completed."); - } - } catch (Exception e) { - String msg = "Error occurred while trying to run a task."; - log.error(msg, e); + } else { + log.info("No device types registered currently. So did not run the monitoring task."); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java index 0f874a1468..75550744ca 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java @@ -22,6 +22,8 @@ package org.wso2.carbon.policy.mgt.core.task; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; @@ -29,7 +31,6 @@ import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; -import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo; import java.util.HashMap; @@ -38,47 +39,64 @@ import java.util.Map; public class TaskScheduleServiceImpl implements TaskScheduleService { private static Log log = LogFactory.getLog(TaskScheduleServiceImpl.class); + private PolicyConfiguration policyConfiguration; + + + public TaskScheduleServiceImpl() { + this.policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getPolicyConfiguration(); + } @Override public void startTask(int monitoringFrequency) throws PolicyMonitoringTaskException { - if (monitoringFrequency <= 0) { - throw new PolicyMonitoringTaskException("Time interval cannot be 0 or less than 0."); - } - try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); - taskService.registerTaskType(PolicyManagementConstants.TASK_TYPE); - if (log.isDebugEnabled()) { - log.debug("Monitoring task is started for the tenant id " + tenantId); + if (policyConfiguration.getMonitoringEnable()) { + + if (monitoringFrequency <= 0) { + throw new PolicyMonitoringTaskException("Time interval cannot be 0 or less than 0."); } + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); + taskService.registerTaskType(PolicyManagementConstants.MONITORING_TASK_TYPE); - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE); + if (log.isDebugEnabled()) { + log.debug("Monitoring task is started for the tenant id " + tenantId); + } - TriggerInfo triggerInfo = new TriggerInfo(); + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); - triggerInfo.setIntervalMillis(monitoringFrequency); - triggerInfo.setRepeatCount(-1); + TriggerInfo triggerInfo = new TriggerInfo(); + triggerInfo.setIntervalMillis(monitoringFrequency); + triggerInfo.setRepeatCount(-1); - Map properties = new HashMap<>(); - properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); + Map properties = new HashMap<>(); + properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); - String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); - TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo); + if (!taskManager.isTaskScheduled(taskName)) { - taskManager.registerTask(taskInfo); - taskManager.rescheduleTask(taskInfo.getName()); + TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, + properties, triggerInfo); + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new PolicyMonitoringTaskException("Monitoring task is already started for this tenant " + + tenantId); + } - } catch (TaskException e) { - String msg = "Error occurred while creating the task for tenant " + PrivilegedCarbonContext. - getThreadLocalCarbonContext().getTenantId(); - log.error(msg, e); - throw new PolicyMonitoringTaskException(msg, e); - } + } catch (TaskException e) { + throw new PolicyMonitoringTaskException("Error occurred while creating the task for tenant " + + PrivilegedCarbonContext. + getThreadLocalCarbonContext().getTenantId(), e); + } + } else { + throw new PolicyMonitoringTaskException("Policy monitoring is not enabled in the cdm-config.xml."); + } } @@ -86,15 +104,14 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { public void stopTask() throws PolicyMonitoringTaskException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE); + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); taskManager.deleteTask(taskName); } catch (TaskException e) { - String msg = "Error occurred while deleting the task for tenant " + PrivilegedCarbonContext. - getThreadLocalCarbonContext().getTenantId(); - log.error(msg, e); - throw new PolicyMonitoringTaskException(msg, e); + throw new PolicyMonitoringTaskException("Error occurred while deleting the task for tenant " + + PrivilegedCarbonContext. + getThreadLocalCarbonContext().getTenantId(), e); } } @@ -102,31 +119,34 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { public void updateTask(int monitoringFrequency) throws PolicyMonitoringTaskException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE); + if (taskManager.isTaskScheduled(taskName)) { - taskManager.deleteTask(taskName); - - TriggerInfo triggerInfo = new TriggerInfo(); + taskManager.deleteTask(taskName); + TriggerInfo triggerInfo = new TriggerInfo(); + triggerInfo.setIntervalMillis(monitoringFrequency); + triggerInfo.setRepeatCount(-1); - triggerInfo.setIntervalMillis(monitoringFrequency); - triggerInfo.setRepeatCount(-1); + Map properties = new HashMap<>(); + properties.put("tenantId", String.valueOf(tenantId)); - Map properties = new HashMap<>(); - properties.put("tenantId", String.valueOf(tenantId)); + TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, properties, + triggerInfo); - TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo); - - taskManager.registerTask(taskInfo); - taskManager.rescheduleTask(taskInfo.getName()); + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new PolicyMonitoringTaskException("Monitoring task has not been started for this tenant " + + tenantId + ". Please start the task first."); + } } catch (TaskException e) { - String msg = "Error occurred while updating the task for tenant " + PrivilegedCarbonContext. - getThreadLocalCarbonContext().getTenantId(); - log.error(msg, e); - throw new PolicyMonitoringTaskException(msg, e); + throw new PolicyMonitoringTaskException("Error occurred while updating the task for tenant " + + PrivilegedCarbonContext. + getThreadLocalCarbonContext().getTenantId(), e); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java index 2c033151ca..e8354b3e99 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java @@ -32,14 +32,18 @@ public final class PolicyManagementConstants { public static final String BLOCK = "BLOCK"; - public static final String TASK_TYPE = "MONITORING_TASK"; - public static final String TASK_NAME = "MONITORING"; - public static final String TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.task.MonitoringTask"; + public static final String MONITORING_TASK_TYPE = "MONITORING_TASK"; + public static final String MONITORING_TASK_NAME = "MONITORING"; + public static final String MONITORING_TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.task.MonitoringTask"; public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER"; public static final String DM_CACHE = "DM_CACHE"; + public static final String DELEGATION_TASK_TYPE = "DELEGATION__TASK"; + public static final String DELEGATION_TASK_NAME = "DELEGATION"; + public static final String DELEGATION_TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask"; + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 1beea7f39f..198913c055 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; @@ -41,6 +42,7 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.ObjectOutputStream; import java.util.ArrayList; +import java.util.HashMap; import java.util.Hashtable; import java.util.List; @@ -140,9 +142,29 @@ public class PolicyManagerUtil { return data; } + public static boolean convertIntToBoolean(int x) { - public static Cache getCacheManagerImpl(){ + if (x == 1) { + return true; + } else { + return false; + } + } + + + public static Cache getCacheManagerImpl() { return Caching.getCacheManagerFactory() - .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants.DM_CACHE); + .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants + .DM_CACHE); + } + + + public static HashMap covertDeviceListToMap(List devices) { + + HashMap deviceHashMap = new HashMap<>(); + for (Device device : devices) { + deviceHashMap.put(device.getId(), device); + } + return deviceHashMap; } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java index 8cad5f5b78..a01ff15567 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java @@ -26,11 +26,23 @@ import org.testng.annotations.BeforeSuite; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +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.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; +import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.common.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import org.wso2.carbon.policy.mgt.core.services.PolicyMonitoringServiceTest; +import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import javax.sql.DataSource; @@ -50,6 +62,13 @@ public abstract class BasePolicyManagementDAOTest { public void setupDataSource() throws Exception { this.initDatSource(); this.initSQLScript(); + this.initialize(); + this.initiatePrivilegedCaronContext(); + DeviceConfigurationManager.getInstance().initConfig(); + } + + public void initialize() throws TaskException { + } public void initDatSource() throws Exception { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java index 9c0e62e46a..f1fdfed8e1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java @@ -31,11 +31,13 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; import org.wso2.carbon.policy.mgt.common.Policy; -import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; -import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; @@ -69,19 +71,19 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { List devices = service.getAllDevices(ANDROID); for (Policy policy : policies) { - log.debug(policy.getPolicyName() + "-----P"); + log.debug("Policy Name : " + policy.getPolicyName()); } for (Device device : devices) { - log.debug(device.getDeviceIdentifier() + " ----- D"); + log.debug("Device Name : " + device.getDeviceIdentifier()); } identifier.setType(ANDROID); identifier.setId(devices.get(0).getDeviceIdentifier()); - PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl(); - - administratorPoint.setPolicyUsed(identifier, policies.get(0)); +// PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl(); +// +// administratorPoint.setPolicyUsed(identifier, policies.get(0)); } @@ -114,9 +116,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { DeviceManagementDataHolder.getInstance().setOperationManager(operationManager); - log.debug(policy.getId()); - log.debug(policy.getPolicyName()); - log.debug(policy.getCompliance()); + if (policy != null) { + log.debug(policy.getId()); + log.debug(policy.getPolicyName()); + log.debug(policy.getCompliance()); + } MonitoringManager monitoringManager = new MonitoringManagerImpl(); @@ -135,14 +139,13 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { PolicyComplianceException { - PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), monitoringServiceTest); DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl(); - // PolicyManager policyManagerService = new PolicyManagerImpl(); + // PolicyManager policyManagerService = new PolicyManagerImpl(); List devices = adminService.getAllDevices(); @@ -157,14 +160,17 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { PolicyManager manager = new PolicyManagerImpl(); Policy policy = manager.getAppliedPolicyToDevice(identifier); - Object ob = new Object(); + if(policy != null) { + Object ob = new Object(); - monitoringServiceTest.checkPolicyCompliance(identifier, policy, ob); + monitoringServiceTest.checkPolicyCompliance(identifier, policy, ob); + } } @Test(dependsOnMethods = ("checkComplianceFromMonitoringService")) - public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, PolicyManagementException { + public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, + PolicyManagementException { PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), @@ -189,4 +195,5 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { monitoringManager.checkPolicyCompliance(identifier, ob); } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index ca85ab1c98..ffc592b335 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -33,12 +33,6 @@ import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; -import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; -import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; -import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; -import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; -import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; -import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; import org.wso2.carbon.policy.mgt.core.util.*; import java.sql.SQLException; @@ -83,13 +77,18 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("addDeviceType")) - public void addDevice() throws DeviceManagementDAOException, DeviceManagementException { + public void addDevice() throws DeviceManagementException, PolicyManagementException { DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); DeviceType type = DeviceTypeCreator.getDeviceType(); devices = DeviceCreator.getDeviceList(type); + devices.addAll(DeviceCreator.getDeviceList2(type)); + devices.addAll(DeviceCreator.getDeviceList3(type)); + devices.addAll(DeviceCreator.getDeviceList4(type)); + devices.addAll(DeviceCreator.getDeviceList5(type)); + devices.addAll(DeviceCreator.getDeviceList6(type)); try { DeviceManagementDAOFactory.beginTransaction(); @@ -97,38 +96,16 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { int id = deviceDAO.addDevice(type.getId(), device, -1234); enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234); } + } catch (TransactionManagementException e) { + throw new PolicyManagementException("Error occurred while adding device enrolment", e); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); - throw new DeviceManagementException("Error occurred while adding dummy device info", e); - } catch (TransactionManagementException e) { - throw new DeviceManagementException("Error occurred while initiating a transaction to add dummy " + - "device info", e); + throw new PolicyManagementException("Error occurred while adding device information", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - log.debug("--- Printing device taken by calling the device dao layer by tenant id and device type."); - List devices2 = null; - try { - DeviceManagementDAOFactory.openConnection(); - List devices = deviceDAO.getDevices(-1234); - - log.debug("--- Printing device taken by calling the device dao layer by tenant id."); - for (Device device : devices) { - log.debug(device.getDeviceIdentifier()); - } - devices2 = deviceDAO.getDevices("android", -1234); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - for (Device device : devices2) { - log.debug(device.getDeviceIdentifier()); - } - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); PolicyManagementDataHolder.getInstance().setDeviceManagementService(service); @@ -136,6 +113,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { log.debug("Printing device taken by calling the service layer with device type."); List devices3 = service.getAllDevices("android"); + log.debug("Device list size ...! " + devices3.size()); for (Device device : devices3) { log.debug(device.getDeviceIdentifier()); } @@ -145,50 +123,53 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("addDevice")) public void addFeatures() throws FeatureManagementException { - FeatureManager featureManager = new FeatureManagerImpl(); + //This test case was removed because architecture was changed + +// FeatureManager featureManager = new FeatureManagerImpl(); featureList = FeatureCreator.getFeatureList(); - //featureManager.addFeatures(featureList); - for (Feature feature : featureList) { -// featureManager.addFeature(feature); - } +// featureManager.addFeatures(featureList); +// for (Feature feature : featureList) { +// featureManager.addFeature(feature); +// } } @Test(dependsOnMethods = ("addFeatures")) public void addProfileFeatures() throws ProfileManagementException { - ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); - profileManager.addProfile(profile); - profileFeatureList = profile.getProfileFeaturesList(); +// ProfileManager profileManager = new ProfileManagerImpl(); +// Profile profile = ProfileCreator.getProfile2(FeatureCreator.getFeatureList2()); +// profileManager.addProfile(profile); +// profileFeatureList = profile.getProfileFeaturesList(); } @Test(dependsOnMethods = ("addProfileFeatures")) public void addPolicy() throws PolicyManagementException, ProfileManagementException { - ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); - profileManager.addProfile(profile); - PolicyManager policyManager = new PolicyManagerImpl(); +// ProfileManager profileManager = new ProfileManagerImpl(); + Profile profile = ProfileCreator.getProfile5(FeatureCreator.getFeatureList5()); +// profileManager.addProfile(profile); + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); policy = PolicyCreator.createPolicy(profile); - policyManager.addPolicy(policy); + policy = pap.addPolicy(policy); + pap.activatePolicy(policy.getId()); } @Test(dependsOnMethods = ("addPolicy")) public void addPolicyToRole() throws PolicyManagementException { - PolicyManager policyManager = new PolicyManagerImpl(); + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); List roles = new ArrayList(); roles.add("Test_ROLE_01"); roles.add("Test_ROLE_02"); roles.add("Test_ROLE_03"); - policyManager.addPolicyToRole(roles, policy); + pap.addPolicyToRole(roles, policy); } @Test(dependsOnMethods = ("addPolicyToRole")) public void addPolicyToDevice() throws PolicyManagementException { - PolicyManager policyManager = new PolicyManagerImpl(); + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); Device device = DeviceCreator.getSingleDevice(); List deviceIdentifierList = new ArrayList(); @@ -197,29 +178,31 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { deviceIdentifier.setType("android"); deviceIdentifierList.add(deviceIdentifier); - policyManager.addPolicyToDevice(deviceIdentifierList, policy); + pap.addPolicyToDevice(deviceIdentifierList, policy); } @Test(dependsOnMethods = ("addPolicyToDevice")) public void addNewPolicy() throws PolicyManagementException, ProfileManagementException { - ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); - profileManager.addProfile(profile); - PolicyManager policyManager = new PolicyManagerImpl(); - policy = PolicyCreator.createPolicy2(profile); - policyManager.addPolicy(policy); + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); + Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3()); + //pap.addProfile(profile); + // PolicyManager policyManager = new PolicyManagerImpl(); + Policy policy = PolicyCreator.createPolicy2(profile); + policy = pap.addPolicy(policy); + pap.activatePolicy(policy.getId()); } @Test(dependsOnMethods = ("addPolicyToDevice")) public void addThirdPolicy() throws PolicyManagementException, ProfileManagementException { - ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); - profileManager.addProfile(profile); - PolicyManager policyManager = new PolicyManagerImpl(); - policy = PolicyCreator.createPolicy4(profile); - policyManager.addPolicy(policy); + //ProfileManager profileManager = new ProfileManagerImpl(); + Profile profile = ProfileCreator.getProfile4(FeatureCreator.getFeatureList4()); + //profileManager.addProfile(profile); + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); + Policy policy = PolicyCreator.createPolicy4(profile); + policy = pap.addPolicy(policy); + pap.activatePolicy(policy.getId()); } @Test(dependsOnMethods = ("addNewPolicy")) @@ -311,15 +294,32 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("getRoleRelatedPolicy")) public void addSecondPolicy() throws PolicyManagementException, ProfileManagementException { - ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); - profileManager.addProfile(profile); - PolicyManager policyManager = new PolicyManagerImpl(); - policy = PolicyCreator.createPolicy3(profile); - policyManager.addPolicy(policy); + // ProfileManager profileManager = new ProfileManagerImpl(); + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList()); + //profileManager.addProfile(profile); + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); + Policy policy = PolicyCreator.createPolicy3(profile); + policy = pap.addPolicy(policy); + pap.activatePolicy(policy.getId()); } - @Test(dependsOnMethods = ("getDeviceTypeRelatedPolicy")) + @Test(dependsOnMethods = ("addSecondPolicy")) + public void updatedPolicy() throws PolicyManagementException { + PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl(); + Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3()); + Policy policy = PolicyCreator.createPolicy3(profile); + policy.setPolicyName("Policy_05"); + policy = pap.addPolicy(policy); + pap.activatePolicy(policy.getId()); + List users = new ArrayList<>(); + users.add("Udara"); + users.add("Dileesha"); + policy.setUsers(users); + pap.updatePolicy(policy); + pap.activatePolicy(policy.getId()); + } + + @Test(dependsOnMethods = ("updatedPolicy")) public void getRoleRelatedPolicySecondTime() throws PolicyManagementException { PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl(); @@ -381,7 +381,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl(); policyAdministratorPoint.deletePolicy(1); - log.debug("First policy deleted."); + log.debug("First policy deleted..!"); } @@ -395,13 +395,12 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { List devices = service.getAllDevices("android"); for (Policy policy : policies) { - log.debug(policy.getPolicyName() + "-----P"); + log.debug("Policy Name : " + policy.getPolicyName()); } for (Device device : devices) { - log.debug(device.getDeviceIdentifier() + " ----- D"); + log.debug("Device Name : " + device.getDeviceIdentifier()); } - - } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java new file mode 100644 index 0000000000..e1ebc13e9d --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java @@ -0,0 +1,136 @@ +/* + * 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.policy.mgt.core; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +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.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; +import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; + +import java.util.Collections; +import java.util.List; + +public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { + + private static final String ANDROID = "android"; + private static final Log log = LogFactory.getLog(PolicyEvaluationTestCase.class); + + + @BeforeClass + @Override + public void init() throws Exception { + + PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest(); + PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint); + } + + @Test + public void activatePolicies() throws PolicyManagementException, TaskException { + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP(); + + List policies = policyManagerService.getPolicies(ANDROID); + + for (Policy policy : policies) { + log.debug("Policy status : " + policy.getPolicyName() + " - " + policy.isActive() + " - " + policy + .isUpdated() + " Policy id : " + policy.getId()); + + if (!policy.isActive()) { + administratorPoint.activatePolicy(policy.getId()); + } + } + // This cannot be called due to task service cannot be started from the + //administratorPoint.publishChanges(); + } + + @Test(dependsOnMethods = ("activatePolicies")) + public void getEffectivePolicy() throws DeviceManagementException, PolicyEvaluationException { + + log.debug("Getting effective policy for device started .........."); + + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + List devices = service.getAllDevices(ANDROID); + + PolicyEvaluationPoint evaluationPoint = PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint(); + + for (Device device : devices) { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(device.getType()); + identifier.setId(device.getDeviceIdentifier()); + Policy policy = evaluationPoint.getEffectivePolicy(identifier); + + if (policy != null) { + log.debug("Name of the policy applied to device is " + policy.getPolicyName()); + } else { + log.debug("No policy is applied to device."); + } + } + } + + + @Test(dependsOnMethods = ("getEffectivePolicy")) + public void updatePriorities() throws PolicyManagementException, TaskException { + + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP(); + + List policies = administratorPoint.getPolicies(); + + log.debug("Re-enforcing policy started...!"); + + int sixe = policies.size(); + + sortPolicies(policies); + int x = 0; + for (Policy policy : policies) { + policy.setPriorityId(sixe - x); + x++; + } + + administratorPoint.updatePolicyPriorities(policies); + // administratorPoint.publishChanges(); + } + + + @Test(dependsOnMethods = ("updatePriorities")) + public void checkDelegations() { + + log.debug("Delegation methods calls started because tasks cannot be started due to osgi constraints.....!"); + + DelegationTask delegationTask = new DelegationTask(); + delegationTask.execute(); + } + + public void sortPolicies(List policyList) { + Collections.sort(policyList); + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java new file mode 100644 index 0000000000..4895155371 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java @@ -0,0 +1,84 @@ +/* + * 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.policy.mgt.core.services; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; + +import java.util.Collections; +import java.util.List; + +public class SimplePolicyEvaluationTest implements PolicyEvaluationPoint { + + private static final Log log = LogFactory.getLog(SimplePolicyEvaluationTest.class); + + @Override + public Policy getEffectivePolicy(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException { + Policy policy = new Policy(); + + List policyList; + PolicyAdministratorPoint policyAdministratorPoint; + PolicyInformationPoint policyInformationPoint; + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + + try { + if (policyManagerService != null) { + + policyInformationPoint = policyManagerService.getPIP(); + PIPDevice pipDevice = policyInformationPoint.getDeviceData(deviceIdentifier); + policyList = policyInformationPoint.getRelatedPolicies(pipDevice); + + for(Policy pol : policyList) { + log.debug("Policy used in evaluation - Name : " + pol.getPolicyName() ); + } + + sortPolicies(policyList); + if(!policyList.isEmpty()) { + policy = policyList.get(0); + } else { + return null; + } + + policyAdministratorPoint = policyManagerService.getPAP(); + policyAdministratorPoint.setPolicyUsed(deviceIdentifier, policy); + + } + + } catch (PolicyManagementException e) { + String msg = "Error occurred when retrieving the policy related data from policy management service."; + log.error(msg, e); + throw new PolicyEvaluationException(msg, e); + } + return policy; + } + + @Override + public List getEffectiveFeatures(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException { + return null; + } + + public void sortPolicies(List policyList) throws PolicyEvaluationException { + Collections.sort(policyList); + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java index 769c83c514..0fc65b9dca 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java @@ -27,10 +27,12 @@ import java.util.List; public class DeviceCreator { - private static List deviceList = new ArrayList(); + //private static ; public static List getDeviceList(DeviceType deviceType) { + List deviceList = new ArrayList(); + Device device = new Device(); device.setId(1); device.setType(deviceType.getName()); @@ -42,25 +44,131 @@ public class DeviceCreator { enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); device.setEnrolmentInfo(enrolmentInfo); - Device device1 = new Device(); - device1.setId(1); - device1.setType(deviceType.getName()); - device1.setName("Nexus 5"); - device1.setDeviceIdentifier("def456"); - EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo(); - enrolmentInfo1.setOwner("Manoj"); - enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE); - device1.setEnrolmentInfo(enrolmentInfo); +// Device device1 = new Device(); +// device1.setId(2); +// device1.setType(deviceType.getName()); +// device1.setName("Nexus 5"); +// device1.setDeviceIdentifier("def456"); +// EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo(); +// enrolmentInfo1.setOwner("Manoj"); +// enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD); +// enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE); +// device1.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + // deviceList.add(device1); + + return deviceList; + } + + + public static List getDeviceList2 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(2); + device.setType(deviceType.getName()); + device.setName("Apple 5S"); + device.setDeviceIdentifier("def123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Dilshan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + return deviceList; + } + + public static List getDeviceList3 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(3); + device.setType(deviceType.getName()); + device.setName("Apple 6 Large"); + device.setDeviceIdentifier("xxxx123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Harshan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + return deviceList; + } + + public static List getDeviceList4 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(4); + device.setType(deviceType.getName()); + device.setName("HTC M"); + device.setDeviceIdentifier("ppp456"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Dilan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + return deviceList; + } + + public static List getDeviceList5 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(5); + device.setType(deviceType.getName()); + device.setName("Sony Experia L"); + device.setDeviceIdentifier("ssss123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Milan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); deviceList.add(device); - // deviceList.add(device2); + return deviceList; + } + + + public static List getDeviceList6 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(6); + device.setType(deviceType.getName()); + device.setName("Alcatel RTS"); + device.setDeviceIdentifier("ttt123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Dileesha"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + deviceList.add(device); return deviceList; } + public static Device getSingleDevice() { - return deviceList.get(0); + + Device device = new Device(); + device.setId(1); + device.setType("android"); + device.setName("Galaxy S6"); + device.setDeviceIdentifier("abc123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Geeth"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + + return device; } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java index c487e7c6ea..6456773a08 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java @@ -21,10 +21,15 @@ package org.wso2.carbon.policy.mgt.core.util; import org.wso2.carbon.device.mgt.common.Feature; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; public class FeatureCreator { + private static List featureList = new ArrayList(); + + private static HashMap featureMap = new HashMap<>(); + public static List getFeatureList() { Feature feature1 = new Feature(); @@ -119,7 +124,7 @@ public class FeatureCreator { feature11.setDeviceType("android"); - List featureList = new ArrayList(); + List featureList2 = new ArrayList(); featureList.add(feature1); featureList.add(feature2); featureList.add(feature3); @@ -132,6 +137,70 @@ public class FeatureCreator { featureList.add(feature10); featureList.add(feature11); - return featureList; + featureList2.add(feature1); + featureList2.add(feature2); + + + int i = 1; + for (Feature feature : featureList) { + featureMap.put(i, feature); + i++; + } + + return featureList2; + } + + public static List getFeatureList2() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(3)); + featureList2.add(featureMap.get(4)); + + return featureList2; + } + + public static List getFeatureList3() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(5)); + featureList2.add(featureMap.get(6)); + featureList2.add(featureMap.get(7)); + + return featureList2; + } + + public static List getFeatureList4() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(7)); + featureList2.add(featureMap.get(8)); + featureList2.add(featureMap.get(9)); + + return featureList2; + } + + public static List getFeatureList5() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(9)); + featureList2.add(featureMap.get(10)); + featureList2.add(featureMap.get(11)); + featureList2.add(featureMap.get(3)); + + return featureList2; + } + + + public static List getFeatureList6() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(3)); + featureList2.add(featureMap.get(8)); + featureList2.add(featureMap.get(9)); + featureList2.add(featureMap.get(5)); + + return featureList2; } } + + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java index 7ef7ab4a37..a7dbe5c4a6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java @@ -50,7 +50,7 @@ public class PolicyCreator { policy.setPolicyName("Test_Policy_02"); policy.setGeneric(true); policy.setProfile(profile); - policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); + policy.setDevices(DeviceCreator.getDeviceList2(DeviceTypeCreator.getDeviceType())); policy.setCompliance("ENFORCE"); @@ -99,7 +99,7 @@ public class PolicyCreator { policy.setPolicyName("Test_Policy_03"); policy.setGeneric(true); policy.setProfile(profile); - policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); + policy.setDevices(DeviceCreator.getDeviceList3(DeviceTypeCreator.getDeviceType())); List roles = new ArrayList(); roles.add("Role_01"); @@ -138,7 +138,7 @@ public class PolicyCreator { policy.setPolicyName("Test_Policy_04"); policy.setGeneric(true); policy.setProfile(profile); - policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); + policy.setDevices(DeviceCreator.getDeviceList4(DeviceTypeCreator.getDeviceType())); policy.setCompliance("MONITOR"); policy.setOwnershipType("BYOD"); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java index 4bd1392590..19574abdf6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java @@ -41,4 +41,66 @@ public class ProfileCreator { return profile; } + + public static Profile getProfile2(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 2"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } + + public static Profile getProfile3(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 3"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } + + public static Profile getProfile4(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 4"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } + + + public static Profile getProfile5(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 5"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } } + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml new file mode 100644 index 0000000000..0f5861cc1d --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml @@ -0,0 +1,48 @@ + + + + + + + + jdbc/DM_DS + + + + 8 + 100 + 20 + 1000 + + + https://localhost:9443 + admin + admin + + + org.wso2.carbon.policy.mgt + true + 60000 + 5 + 8 + 20 + + + + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml new file mode 100644 index 0000000000..dec2307f1d --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml @@ -0,0 +1,51 @@ + + + + AUTO + + + 2 + + + + org.wso2.carbon.ntask.core.impl.RoundRobinTaskLocationResolver + + + + + + + https://localhost:9448 + + + https://localhost:9443 + + + admin + + + admin + + + + + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/notification-messages.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/notification-messages.xml new file mode 100644 index 0000000000..9b13c5d808 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/notification-messages.xml @@ -0,0 +1,39 @@ + + + Enroll your Device with WSO2 MDM +
Dear {first-name},
+ + You have been registered to the WSO2 MDM. Below is the link to enroll. + + {downloadUrl} + + Best Regards, + + + WSO2 MDM Team. + + + http://www.wso2.com + +
+ + Enroll your Device with WSO2 MDM +
Dear {first-name},
+ +You have been registered to WSO2 MDM with following credentials. +Username: {user-name} +Password: {password} +Below is the link to enroll. + + {downloadUrl} + + Best Regards, + + + WSO2 MDM Team. + + + http://www.wso2.com + +
+
\ No newline at end of file diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml index 7450e52f77..3b7e74c0a1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml @@ -33,8 +33,8 @@ - - + + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index 3263fa8290..f221ba0e78 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -109,7 +109,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATIONS ( APPLICATIONS BLOB DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_applications_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); --- POLICY RELATED TABLES ---- @@ -143,7 +143,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL , + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) @@ -158,6 +160,8 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ID INT(11) NOT NULL AUTO_INCREMENT , DEVICE_ID INT(11) NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, + DEVICE BLOB NOT NULL, POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY @@ -243,8 +247,9 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( - ID INT NOT NULL AUTO_INCREMENT , - DEVICE_ID INT NOT NULL , + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT BLOB NULL , TENANT_ID INT NOT NULL, @@ -314,6 +319,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -345,6 +351,14 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ON UPDATE NO ACTION ); +CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, + PRIMARY KEY (ID) +); + -- POLICY RELATED TABLES FINISHED -- diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml index 5fd31bb67c..24a1f0d80e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml @@ -27,6 +27,7 @@ + \ No newline at end of file diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml new file mode 100644 index 0000000000..a404f17a9e --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml @@ -0,0 +1,156 @@ + + + + + + + org.wso2.carbon.devicemgt + certificate-mgt-feature + 0.9.2-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.certificate.mgt.server.feature + pom + 0.9.2-SNAPSHOT + WSO2 Carbon - Certificate Management Server Feature + http://wso2.org + This feature contains the core bundles required for back-end Certificate Management functionality + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + + + org.bouncycastle.wso2 + bcprov-jdk15on + + + org.bouncycastle.wso2 + bcpkix-jdk15on + + + org.bouncycastle.wso2 + bcmail-jdk15on + + + com.google.code.jscep.wso2 + jscep + + + commons-io.wso2 + commons-io + + + commons-lang.wso2 + commons-lang + + + commons-codec.wso2 + commons-codec + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.carbon.certificate.mgt.server + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:false + + + + + org.wso2.carbon.devicemgt:org.wso2.carbon.certificate.mgt.core:${carbon.device.mgt.version} + + + org.bouncycastle.wso2:bcprov-jdk15on:${bcprov.wso2.version} + + + org.bouncycastle.wso2:bcpkix-jdk15on:${bcpkix.wso2.version} + + + org.bouncycastle.wso2:bcmail-jdk15on:${bcmail.wso2.version} + + + com.google.code.jscep.wso2:jscep:${jscep.version} + + + commons-io.wso2:commons-io:${version.commons.io} + + + commons-lang.wso2:commons-lang:${version.commons.lang} + + + commons-codec.wso2:commons-codec:${version.commons.codec} + + + + org.wso2.carbon.core.server:${carbon.kernel.version} + + + + + + + + diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/build.properties b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..9c86577d76 --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/build.properties @@ -0,0 +1 @@ +custom = true diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf/certificate-config.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf/certificate-config.xml new file mode 100755 index 0000000000..e19786b861 --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf/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/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf/wso2certs.jks b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf/wso2certs.jks new file mode 100644 index 0000000000..d40aca9848 Binary files /dev/null and b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf/wso2certs.jks differ diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf new file mode 100644 index 0000000000..7bae1dd04a --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf @@ -0,0 +1,3 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/wso2certs.jks,target:${installFolder}/../../resources/security/wso2certs.jks,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/certificate-config.xml,target:${installFolder}/../../conf/certificate-config.xml,overwrite:true);\ \ No newline at end of file diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml new file mode 100644 index 0000000000..b34fa8d76e --- /dev/null +++ b/features/certificate-mgt/pom.xml @@ -0,0 +1,41 @@ + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 0.9.2-SNAPSHOT + ../../pom.xml + + + 4.0.0 + org.wso2.carbon.devicemgt + certificate-mgt-feature + 0.9.2-SNAPSHOT + pom + WSO2 Carbon - Certificate Management Feature + http://wso2.org + + + org.wso2.carbon.certificate.mgt.server.feature + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml index 0efa651a73..0f5861cc1d 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml @@ -37,8 +37,11 @@ org.wso2.carbon.policy.mgt + true + 60000 5 8 + 20 diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 44a178ef51..781ea7640b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -1,20 +1,15 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ID INT auto_increment NOT NULL, - NAME VARCHAR(300) NULL DEFAULT NULL, + NAME VARCHAR(300) DEFAULT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, - DESCRIPTION TEXT NULL DEFAULT NULL, - NAME VARCHAR(100) NULL DEFAULT NULL, - DATE_OF_ENROLLMENT BIGINT NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE BIGINT NULL DEFAULT NULL, - OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, - STATUS VARCHAR(15) NULL DEFAULT NULL, - DEVICE_TYPE_ID INT(11) NULL DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL, - OWNER VARCHAR(45) NULL DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + NAME VARCHAR(100) DEFAULT NULL, + DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) @@ -68,10 +63,10 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, OWNER VARCHAR(50) NOT NULL, - OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES @@ -128,12 +123,14 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( CREATE TABLE IF NOT EXISTS DM_POLICY ( ID INT(11) NOT NULL AUTO_INCREMENT , - NAME VARCHAR(45) NULL DEFAULT NULL , + NAME VARCHAR(45) DEFAULT NULL , TENANT_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL , + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) @@ -148,6 +145,8 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ID INT(11) NOT NULL AUTO_INCREMENT , DEVICE_ID INT(11) NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, + DEVICE BLOB NOT NULL, POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY @@ -235,6 +234,7 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT BLOB NULL , TENANT_ID INT NOT NULL, @@ -300,6 +300,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -317,6 +318,15 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ); +CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, + PRIMARY KEY (ID) +); + + CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ID INT NOT NULL AUTO_INCREMENT, COMPLIANCE_STATUS_ID INT NOT NULL, @@ -335,10 +345,10 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, OWNER VARCHAR(50) NOT NULL, - OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES @@ -349,12 +359,12 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( ID INTEGER AUTO_INCREMENT NOT NULL, NAME VARCHAR(50) NOT NULL, APP_IDENTIFIER VARCHAR(50) NOT NULL, - PLATFORM VARCHAR(50) NULL DEFAULT NULL, + PLATFORM VARCHAR(50) DEFAULT NULL, CATEGORY VARCHAR(50) NULL, VERSION VARCHAR(50) NULL, TYPE VARCHAR(50) NULL, - LOCATION_URL VARCHAR(100) NULL DEFAULT NULL, - IMAGE_URL VARCHAR(100) NULL DEFAULT NULL, + LOCATION_URL VARCHAR(100) DEFAULT NULL, + IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index bc04de8732..eb887f68c6 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -3,7 +3,7 @@ -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `DM_DEVICE_TYPE` ( `ID` INT(11) NOT NULL , - `NAME` VARCHAR(300) NULL DEFAULT NULL , + `NAME` VARCHAR(300) DEFAULT NULL , PRIMARY KEY (`ID`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = latin1; @@ -14,16 +14,11 @@ DEFAULT CHARACTER SET = latin1; -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `DM_DEVICE` ( `ID` VARCHAR(20) NOT NULL , - `DESCRIPTION` TEXT NULL DEFAULT NULL , - `NAME` VARCHAR(100) NULL DEFAULT NULL , - `DATE_OF_ENROLLMENT` DATETIME NULL DEFAULT NULL , - `DATE_OF_LAST_UPDATE` DATETIME NULL DEFAULT NULL , - `OWNERSHIP` VARCHAR(45) NULL DEFAULT NULL , - `STATUS` VARCHAR(15) NULL DEFAULT NULL , - `DEVICE_TYPE_ID` INT(11) NULL DEFAULT NULL , - `DEVICE_IDENTIFICATION` VARCHAR(300) NULL DEFAULT NULL , - `OWNER` VARCHAR(45) NULL DEFAULT NULL , - TENANT_ID INTEGER DEFAULT 0, + `DESCRIPTION` TEXT DEFAULT NULL , + `NAME` VARCHAR(100) DEFAULT NULL , + `DEVICE_TYPE_ID` INT(11) DEFAULT NULL , + `DEVICE_IDENTIFICATION` VARCHAR(300) DEFAULT NULL , + `TENANT_ID` INTEGER DEFAULT 0, PRIMARY KEY (`ID`) , INDEX `fk_DM_DEVICE_DM_DEVICE_TYPE2_idx` (`DEVICE_TYPE_ID` ASC) , CONSTRAINT `fk_DM_DEVICE_DM_DEVICE_TYPE2` diff --git a/pom.xml b/pom.xml index c44b195add..2bf3fd8ac9 100644 --- a/pom.xml +++ b/pom.xml @@ -37,15 +37,17 @@ components/device-mgt - components/apimgt-extensions + components/apimgt-extensions components/policy-mgt + components/certificate-mgt components/webapp-authenticator-framework components/oauth-extensions features/device-mgt features/apimgt-extensions - features/policy-mgt + features/policy-mgt features/webapp-authenticator-framework features/oauth-extensions + features/certificate-mgt @@ -133,6 +135,11 @@ org.wso2.carbon.device.mgt.extensions ${carbon.device.mgt.version}
+ + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + ${carbon.device.mgt.version} + org.wso2.carbon.devicemgt org.wso2.carbon.policy.mgt.common @@ -931,6 +938,44 @@ + + org.bouncycastle.wso2 + bcprov-jdk15on + ${bcprov.wso2.version} + + + org.bouncycastle.wso2 + bcpkix-jdk15on + ${bcpkix.wso2.version} + + + org.bouncycastle.wso2 + bcmail-jdk15on + ${bcmail.wso2.version} + + + com.google.code.jscep.wso2 + jscep + ${jscep.version} + + + + commons-codec.wso2 + commons-codec + ${version.commons.codec} + + + + commons-io.wso2 + commons-io + ${version.commons.io} + + + + commons-lang.wso2 + commons-lang + ${version.commons.lang} + @@ -1184,6 +1229,9 @@ 4.4.0 + 1.4.0.wso2v1 + 2.4.0.wso2v1 + 2.6.0.wso2v1 1.4.0 @@ -1193,6 +1241,16 @@ 2.5.11 1.1.wso2v1 1.9.0 + + + 1.49.wso2v1 + 1.49.wso2v1 + 1.49.wso2v1 + [1.40.wso2v1, 1.50.0) + 1.49.wso2v1 + + + 2.0.2.wso2v2