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