Fixed conflicts and merged

This commit is contained in:
milanperera 2015-09-07 12:39:51 +05:30
commit 8d38c37d53
89 changed files with 2957 additions and 914 deletions

View File

@ -47,11 +47,31 @@
<groupId>org.wso2.tomcat</groupId> <groupId>org.wso2.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId> <artifactId>tomcat-servlet-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
@ -78,7 +98,10 @@
org.apache.catalina.core, org.apache.catalina.core,
org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model, org.wso2.carbon.apimgt.api.model,
org.wso2.carbon.apimgt.impl org.wso2.carbon.apimgt.impl,
org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.wso2.carbon.core,
org.wso2.carbon.utils
</Import-Package> </Import-Package>
</instructions> </instructions>
</configuration> </configuration>

View File

@ -25,6 +25,10 @@ import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIStatus; import org.wso2.carbon.apimgt.api.model.APIStatus;
import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
@ -95,4 +99,29 @@ public class APIPublisherUtil {
return uriTemplates; return uriTemplates;
} }
public static String getServerBaseUrl() {
// Hostname
String hostName = "localhost";
try {
hostName = NetworkUtils.getMgtHostName();
} catch (Exception ignored) {
}
// HTTPS port
String mgtConsoleTransport = CarbonUtils.getManagementTransport();
ConfigurationContextService configContextService =
APIPublisherDataHolder.getInstance().getConfigurationContextService();
int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
int httpsProxyPort =
CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
mgtConsoleTransport);
if (httpsProxyPort > 0) {
port = httpsProxyPort;
}
return "https://" + hostName + ":" + port;
}
public static String getApiEndpointUrl(String context) {
return getServerBaseUrl() + context;
}
} }

View File

@ -19,10 +19,12 @@
package org.wso2.carbon.apimgt.webapp.publisher.internal; package org.wso2.carbon.apimgt.webapp.publisher.internal;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.utils.ConfigurationContextService;
public class APIPublisherDataHolder { public class APIPublisherDataHolder {
private APIPublisherService apiPublisherService; private APIPublisherService apiPublisherService;
private ConfigurationContextService configurationContextService;
private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder();
@ -41,4 +43,12 @@ public class APIPublisherDataHolder {
this.apiPublisherService = apiPublisherService; this.apiPublisherService = apiPublisherService;
} }
public void setConfigurationContextService(ConfigurationContextService configurationContextService) {
this.configurationContextService = configurationContextService;
}
public ConfigurationContextService getConfigurationContextService() {
return configurationContextService;
}
} }

View File

@ -25,12 +25,21 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl;
import org.wso2.carbon.utils.ConfigurationContextService;
/**
* @scr.component name="org.wso2.carbon.apimgt.webapp.publisher" immediate="true"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService"
* cardinality="0..1"
* policy="dynamic"
* bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
*/
public class APIPublisherServiceComponent { public class APIPublisherServiceComponent {
private static Log log = LogFactory.getLog(APIPublisherServiceComponent.class); private static Log log = LogFactory.getLog(APIPublisherServiceComponent.class);
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -48,7 +57,6 @@ public class APIPublisherServiceComponent {
} }
} }
@SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
//do nothing //do nothing
} }
@ -63,7 +71,6 @@ public class APIPublisherServiceComponent {
APIPublisherService publisher = new APIPublisherServiceImpl(); APIPublisherService publisher = new APIPublisherServiceImpl();
APIPublisherDataHolder.getInstance().setApiPublisherService(publisher); APIPublisherDataHolder.getInstance().setApiPublisherService(publisher);
bundleContext.registerService(APIPublisherService.class, publisher, null); bundleContext.registerService(APIPublisherService.class, publisher, null);
} }
protected void setAPIManagerConfigurationService(APIManagerConfigurationService service) { protected void setAPIManagerConfigurationService(APIManagerConfigurationService service) {
@ -74,4 +81,18 @@ public class APIPublisherServiceComponent {
//do nothing //do nothing
} }
protected void setConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Setting ConfigurationContextService");
}
APIPublisherDataHolder.getInstance().setConfigurationContextService(configurationContextService);
}
protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Un-setting ConfigurationContextService");
}
APIPublisherDataHolder.getInstance().setConfigurationContextService(null);
}
} }

View File

@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
@ -53,15 +54,21 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext(); ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && param.isEmpty()) && Boolean.parseBoolean(param); boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) { if (isManagedApi) {
APIConfig apiConfig = this.buildApiConfig(servletContext); APIConfig apiConfig = this.buildApiConfig(servletContext);
try { try {
apiConfig.init(); apiConfig.init();
API api = APIPublisherUtil.getAPI(apiConfig); API api = APIPublisherUtil.getAPI(apiConfig);
APIPublisherDataHolder.getInstance().getApiPublisherService().publishAPI(api); APIPublisherService apiPublisherService =
APIPublisherDataHolder.getInstance().getApiPublisherService();
if (apiPublisherService == null) {
throw new IllegalStateException("API Publisher service is not initialized properly");
}
apiPublisherService.publishAPI(api);
} catch (Throwable e) { } catch (Throwable e) {
/* Throwable is caught as none of the RuntimeExceptions that can potentially occur at this point /* Throwable is caught as none of the RuntimeExceptions that can potentially occur at this point
does not seem to be logged anywhere else within the framework */ does not seem to be logged anywhere else within the framework */
@ -110,6 +117,7 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured"); log.debug("'managed-api-endpoint' attribute is not configured");
} }
endpoint = APIPublisherUtil.getApiEndpointUrl(context);
} }
apiConfig.setEndpoint(endpoint); apiConfig.setEndpoint(endpoint);
@ -122,17 +130,25 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
apiConfig.setOwner(owner); apiConfig.setOwner(owner);
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED); String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED);
boolean isSecured = boolean isSecured;
(isSecuredParam != null && !isSecuredParam.isEmpty()) && Boolean.parseBoolean(isSecuredParam); if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " +
"which is 'true'");
}
isSecured = false;
} else {
isSecured = Boolean.parseBoolean(isSecuredParam);
}
apiConfig.setSecured(isSecured); apiConfig.setSecured(isSecured);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) { if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the defaults, " + log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " +
"which are 'http' and 'https'"); "which is 'https'");
} }
transports = "http,https"; transports = "https";
} }
apiConfig.setTransports(transports); apiConfig.setTransports(transports);

View File

@ -27,7 +27,6 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId> <artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>0.9.2-SNAPSHOT</version> <version>0.9.2-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>

View File

@ -52,9 +52,9 @@ import org.jscep.transaction.Nonce;
import org.jscep.transaction.TransactionId; import org.jscep.transaction.TransactionId;
import org.wso2.carbon.certificate.mgt.core.dto.CAStatus; 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.dto.SCEPResponse;
import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.util.CommonUtil; 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 javax.security.auth.x500.X500Principal;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -64,17 +64,19 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.KeyPairGenerator; import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.Security; import java.security.Security;
import java.security.SignatureException; import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateExpiredException;
@ -155,10 +157,9 @@ public class CertificateGenerator {
keyPairGenerator.initialize(ConfigurationUtil.RSA_KEY_LENGTH, new SecureRandom()); keyPairGenerator.initialize(ConfigurationUtil.RSA_KEY_LENGTH, new SecureRandom());
KeyPair pair = keyPairGenerator.generateKeyPair(); KeyPair pair = keyPairGenerator.generateKeyPair();
X500Principal principal = new X500Principal(ConfigurationUtil.DEFAULT_PRINCIPAL); X500Principal principal = new X500Principal(ConfigurationUtil.DEFAULT_PRINCIPAL);
BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
principal, serial, validityBeginDate, validityEndDate, principal, CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate,
principal, pair.getPublic()); principal, pair.getPublic());
ContentSigner contentSigner = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA) ContentSigner contentSigner = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA)
.setProvider(ConfigurationUtil.PROVIDER).build( .setProvider(ConfigurationUtil.PROVIDER).build(
@ -171,6 +172,8 @@ public class CertificateGenerator {
certificate.verify(certificate.getPublicKey()); certificate.verify(certificate.getPublicKey());
saveCertInKeyStore(certificate);
return certificate; return certificate;
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
String errorMsg = "No such algorithm found when generating certificate"; String errorMsg = "No such algorithm found when generating certificate";
@ -279,7 +282,59 @@ public class CertificateGenerator {
} }
} }
public static X509Certificate generateCertificateFromCSR(PrivateKey privateKey, public boolean verifySignature(String headerSignature) throws KeystoreException {
Certificate certificate = extractCertificateFromSignature(headerSignature);
return (certificate != null);
}
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {
if (headerSignature == null || headerSignature.isEmpty()) {
return null;
}
try {
KeyStoreReader keyStoreReader = new KeyStoreReader();
CMSSignedData signedData = new CMSSignedData(Base64.decodeBase64(headerSignature.getBytes()));
Store reqStore = signedData.getCertificates();
@SuppressWarnings("unchecked")
Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);
if (reqCerts != null && reqCerts.size() > 0) {
CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509);
X509CertificateHolder holder = reqCerts.iterator().next();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
X509Certificate reqCert = (X509Certificate) certificateFactory.
generateCertificate(byteArrayInputStream);
if(reqCert != null && reqCert.getSerialNumber() != null) {
Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias(
reqCert.getSerialNumber().toString());
if (lookUpCertificate != null && (lookUpCertificate instanceof X509Certificate)) {
return (X509Certificate)lookUpCertificate;
}
}
}
} catch (CMSException e) {
String errorMsg = "CMSException when decoding certificate signature";
log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "IOException when decoding certificate signature";
log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e);
} catch (CertificateException e) {
String errorMsg = "CertificateException when decoding certificate signature";
log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e);
}
return null;
}
public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
PKCS10CertificationRequest request, PKCS10CertificationRequest request,
String issueSubject) String issueSubject)
throws KeystoreException { throws KeystoreException {
@ -288,9 +343,21 @@ public class CertificateGenerator {
Date validityBeginDate = commonUtil.getValidityStartDate(); Date validityBeginDate = commonUtil.getValidityStartDate();
Date validityEndDate = commonUtil.getValidityEndDate(); 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( X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
new X500Name(issueSubject), BigInteger.valueOf(System.currentTimeMillis()), new X500Name(issueSubject), CommonUtil.generateSerialNumber(),
validityBeginDate, validityEndDate, request.getSubject(), request.getSubjectPublicKeyInfo()); validityBeginDate, validityEndDate, certSubject, request.getSubjectPublicKeyInfo());
ContentSigner sigGen; ContentSigner sigGen;
X509Certificate issuedCert; X509Certificate issuedCert;
@ -302,6 +369,8 @@ public class CertificateGenerator {
issuedCert = new JcaX509CertificateConverter().setProvider( issuedCert = new JcaX509CertificateConverter().setProvider(
ConfigurationUtil.PROVIDER).getCertificate( ConfigurationUtil.PROVIDER).getCertificate(
certificateBuilder.build(sigGen)); certificateBuilder.build(sigGen));
saveCertInKeyStore(issuedCert);
} catch (CertIOException e) { } catch (CertIOException e) {
String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR"; String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR";
log.error(errorMsg, e); log.error(errorMsg, e);
@ -442,11 +511,25 @@ public class CertificateGenerator {
String errorMsg = "Input output issue occurred in getCACert"; String errorMsg = "Input output issue occurred in getCACert";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e); throw new KeystoreException(errorMsg, e);
} catch (KeystoreException e) { }
String errorMsg = "Keystore reading error occurred when handling profile request"; }
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); log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e); throw new KeystoreException(errorMsg, e);
} }
} }
} }

View File

@ -24,6 +24,7 @@ import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.KeyStore; import java.security.KeyStore;
@ -62,7 +63,7 @@ public class KeyStoreReader {
log.error(errorMsg, e); log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e); throw new KeystoreException(errorMsg, e);
} catch (CertificateException e) { } catch (CertificateException e) {
String errorMsg = "Certificate expired when loading KeyStore"; String errorMsg = "CertificateException when loading KeyStore";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e); throw new KeystoreException(errorMsg, e);
} catch (IOException e) { } catch (IOException e) {
@ -82,14 +83,62 @@ public class KeyStoreReader {
return keystore; return keystore;
} }
KeyStore loadMDMKeyStore() throws KeystoreException { 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, return loadKeyStore(ConfigurationUtil.CERTIFICATE_KEYSTORE, ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE,
ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD); 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 { public Certificate getCACertificate() throws KeystoreException {
KeyStore keystore = loadMDMKeyStore(); KeyStore keystore = loadCertificateKeyStore();
Certificate caCertificate; Certificate caCertificate;
try { try {
@ -109,7 +158,7 @@ public class KeyStoreReader {
PrivateKey getCAPrivateKey() throws KeystoreException { PrivateKey getCAPrivateKey() throws KeystoreException {
KeyStore keyStore = loadMDMKeyStore(); KeyStore keyStore = loadCertificateKeyStore();
PrivateKey caPrivateKey; PrivateKey caPrivateKey;
try { try {
caPrivateKey = (PrivateKey) (keyStore.getKey( caPrivateKey = (PrivateKey) (keyStore.getKey(
@ -138,7 +187,7 @@ public class KeyStoreReader {
public Certificate getRACertificate() throws KeystoreException { public Certificate getRACertificate() throws KeystoreException {
KeyStore keystore = loadMDMKeyStore(); KeyStore keystore = loadCertificateKeyStore();
Certificate raCertificate; Certificate raCertificate;
try { try {
raCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.RA_CERT_ALIAS)); raCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.RA_CERT_ALIAS));
@ -155,9 +204,28 @@ public class KeyStoreReader {
return raCertificate; return raCertificate;
} }
public Certificate getCertificateByAlias(String alias) throws KeystoreException {
KeyStore keystore = loadCertificateKeyStore();
Certificate raCertificate;
try {
raCertificate = keystore.getCertificate(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 { PrivateKey getRAPrivateKey() throws KeystoreException {
KeyStore keystore = loadMDMKeyStore(); KeyStore keystore = loadCertificateKeyStore();
PrivateKey raPrivateKey; PrivateKey raPrivateKey;
try { try {
raPrivateKey = (PrivateKey) (keystore.getKey( raPrivateKey = (PrivateKey) (keystore.getKey(

View File

@ -21,6 +21,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl;
/** /**
@ -38,7 +39,7 @@ public class CertificateManagementServiceComponent {
} }
BundleContext bundleContext = componentContext.getBundleContext(); BundleContext bundleContext = componentContext.getBundleContext();
bundleContext.registerService(CertificateManagementServiceImpl.class.getName(), bundleContext.registerService(CertificateManagementService.class.getName(),
CertificateManagementServiceImpl.getInstance(), null); CertificateManagementServiceImpl.getInstance(), null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {

View File

@ -33,17 +33,22 @@ public interface CertificateManagementService {
Certificate getRACertificate() throws KeystoreException; Certificate getRACertificate() throws KeystoreException;
public List<X509Certificate> getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException; List<X509Certificate> getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException;
public X509Certificate generateX509Certificate() throws KeystoreException; X509Certificate generateX509Certificate() throws KeystoreException;
public SCEPResponse getCACertSCEP() throws KeystoreException; SCEPResponse getCACertSCEP() throws KeystoreException;
public byte[] getCACapsSCEP(); byte[] getCACapsSCEP();
public byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException; byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException;
public X509Certificate generateCertificateFromCSR(PrivateKey privateKey, X509Certificate generateCertificateFromCSR(PrivateKey privateKey, PKCS10CertificationRequest request,
PKCS10CertificationRequest request,
String issueSubject) throws KeystoreException; String issueSubject) throws KeystoreException;
Certificate getCertificateByAlias(String alias) throws KeystoreException;
boolean verifySignature(String headerSignature) throws KeystoreException;
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException;
} }

View File

@ -84,4 +84,16 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe
String issueSubject) throws KeystoreException { String issueSubject) throws KeystoreException {
return certificateGenerator.generateCertificateFromCSR(privateKey, request, issueSubject); return certificateGenerator.generateCertificateFromCSR(privateKey, request, issueSubject);
} }
public Certificate getCertificateByAlias(String alias) throws KeystoreException {
return keyStoreReader.getCertificateByAlias(alias);
}
public boolean verifySignature(String headerSignature) throws KeystoreException {
return certificateGenerator.verifySignature(headerSignature);
}
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {
return certificateGenerator.extractCertificateFromSignature(headerSignature);
}
} }

View File

@ -17,6 +17,7 @@
*/ */
package org.wso2.carbon.certificate.mgt.core.util; package org.wso2.carbon.certificate.mgt.core.util;
import java.math.BigInteger;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
@ -40,4 +41,8 @@ public class CommonUtil {
return calendar.getTime(); return calendar.getTime();
} }
public static synchronized BigInteger generateSerialNumber() {
return BigInteger.valueOf(System.currentTimeMillis());
}
} }

View File

@ -59,15 +59,15 @@ public class ConfigurationUtil {
private static ConfigurationUtil configurationUtil; private static ConfigurationUtil configurationUtil;
private static final String[] emmConfigEntryNames = { CA_CERT_ALIAS, RA_CERT_ALIAS, private static final String[] certificateConfigEntryNames = { CA_CERT_ALIAS, RA_CERT_ALIAS,
CERTIFICATE_KEYSTORE, PATH_CERTIFICATE_KEYSTORE, CERTIFICATE_KEYSTORE_PASSWORD, CERTIFICATE_KEYSTORE, PATH_CERTIFICATE_KEYSTORE, CERTIFICATE_KEYSTORE_PASSWORD,
KEYSTORE_CA_CERT_PRIV_PASSWORD, KEYSTORE_RA_CERT_PRIV_PASSWORD }; KEYSTORE_CA_CERT_PRIV_PASSWORD, KEYSTORE_RA_CERT_PRIV_PASSWORD };
private static Map<String, String> configMap; private static Map<String, String> configMap;
private static Map<String, String> readEMMConfigurations() throws KeystoreException { private static Map<String, String> readCertificateConfigurations() throws KeystoreException {
String emmConfLocation = System.getProperty(CONF_LOCATION) + File.separator + CERTIFICATE_CONFIG_XML; String certConfLocation = System.getProperty(CONF_LOCATION) + File.separator + CERTIFICATE_CONFIG_XML;
if (configurationUtil == null || configMap == null) { if (configurationUtil == null || configMap == null) {
@ -76,28 +76,28 @@ public class ConfigurationUtil {
Document document; Document document;
try { try {
File fXmlFile = new File(emmConfLocation); File fXmlFile = new File(certConfLocation);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.parse(fXmlFile); document = documentBuilder.parse(fXmlFile);
} catch (ParserConfigurationException e) { } catch (ParserConfigurationException e) {
throw new KeystoreException("Error parsing configuration in ios-config.xml file"); throw new KeystoreException("Error parsing configuration in certificate-config.xml file");
} catch (SAXException e) { } catch (SAXException e) {
throw new KeystoreException("SAX exception in ios-config.xml file"); throw new KeystoreException("SAX exception in certificate-config.xml file");
} catch (IOException e) { } catch (IOException e) {
throw new KeystoreException("Error reading ios-config.xml file"); throw new KeystoreException("Error reading certificate-config.xml file");
} }
for (String configEntry : emmConfigEntryNames) { for (String configEntry : certificateConfigEntryNames) {
NodeList elements = document.getElementsByTagName(configEntry); NodeList elements = document.getElementsByTagName(configEntry);
if (elements != null && elements.getLength() > 0) { if (elements != null && elements.getLength() > 0) {
configMap.put(configEntry, elements.item(0).getTextContent()); configMap.put(configEntry, elements.item(0).getTextContent());
} }
} }
String emmKeyStoreLocation = replaceCarbonHomeEnvEntry(configMap.get(PATH_CERTIFICATE_KEYSTORE)); String certKeyStoreLocation = replaceCarbonHomeEnvEntry(configMap.get(PATH_CERTIFICATE_KEYSTORE));
if (emmKeyStoreLocation != null) { if (certKeyStoreLocation != null) {
configMap.put(PATH_CERTIFICATE_KEYSTORE, emmKeyStoreLocation); configMap.put(PATH_CERTIFICATE_KEYSTORE, certKeyStoreLocation);
} }
} }
@ -106,7 +106,7 @@ public class ConfigurationUtil {
public static String getConfigEntry(final String entry) throws KeystoreException { public static String getConfigEntry(final String entry) throws KeystoreException {
Map<String, String> configurationMap = readEMMConfigurations(); Map<String, String> configurationMap = readCertificateConfigurations();
String configValue = configurationMap.get(entry); String configValue = configurationMap.get(entry);
if (configValue == null) { if (configValue == null) {

View File

@ -19,6 +19,7 @@ public class CertificateGeneratorTestSuite {
private static final String CA_CERT_PEM = "src/test/resources/ca_cert.pem"; 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 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 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(); private final CertificateGenerator certificateGenerator = new CertificateGenerator();
@Test @Test
@ -42,17 +43,18 @@ public class CertificateGeneratorTestSuite {
} }
} }
@Test // @Test
public void testGenerateX509Certificate() { // public void testGenerateX509Certificate() {
try { // try {
X509Certificate certificate = certificateGenerator.generateX509Certificate(); // System.setProperty(ConfigurationUtil.CONF_LOCATION, CERTIFICATE_CONFIG_PATH);
// X509Certificate certificate = certificateGenerator.generateX509Certificate();
Assert.assertNotNull(certificate, "Certificate received"); //
Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509); // Assert.assertNotNull(certificate, "Certificate received");
} catch (KeystoreException e) { // Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509);
Assert.fail("Error occurred while generating X509 certificate ", e); // } catch (KeystoreException e) {
} // Assert.fail("Error occurred while generating X509 certificate ", e);
} // }
// }
// @Test // @Test
// public void testGetPKIMessage() { // public void testGetPKIMessage() {
@ -63,17 +65,17 @@ public class CertificateGeneratorTestSuite {
// } // }
// } // }
@Test // @Test
public void testGenerateCertificateFromCSR() { // public void testGenerateCertificateFromCSR() {
try { // try {
X509Certificate certificate = certificateGenerator.generateX509Certificate(); // X509Certificate certificate = certificateGenerator.generateX509Certificate();
//
Assert.assertNotNull(certificate, "Certificate received"); // Assert.assertNotNull(certificate, "Certificate received");
Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509); // Assert.assertEquals(certificate.getType(), ConfigurationUtil.X_509);
} catch (KeystoreException e) { // } catch (KeystoreException e) {
Assert.fail("Error occurred while generating certificate ", e); // Assert.fail("Error occurred while generating certificate from CSR ", e);
} // }
} // }
// @Test // @Test
// public void testGetSignerKey() { // public void testGetSignerKey() {

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<CertificateConfigurations> <CertificateConfigurations>
<CertificateKeystore> <CertificateKeystore>
<!-- EMM Keystore file location--> <!-- Certificate Keystore file location-->
<CertificateKeystoreLocation>${carbon.home}/repository/resources/security/wso2cert.jks</CertificateKeystoreLocation> <CertificateKeystoreLocation>${carbon.home}/repository/resources/security/wso2certs.jks</CertificateKeystoreLocation>
<!-- EMM Keystore type (JKS/PKCS12 etc.)--> <!-- Certificate Keystore type (JKS/PKCS12 etc.)-->
<CertificateKeystoreType>JKS</CertificateKeystoreType> <CertificateKeystoreType>JKS</CertificateKeystoreType>
<!-- EMM Keystore password--> <!-- Certificate Keystore password-->
<CertificateKeystorePassword>wso2carbon</CertificateKeystorePassword> <CertificateKeystorePassword>wso2carbon</CertificateKeystorePassword>
<!-- Certificate authority certificate alias --> <!-- Certificate authority certificate alias -->
<CACertAlias>cacert</CACertAlias> <CACertAlias>cacert</CACertAlias>

View File

@ -40,7 +40,8 @@ public class EnrolmentInfo implements Serializable{
private Status status; private Status status;
private String owner; private String owner;
public EnrolmentInfo() {} public EnrolmentInfo() {
}
public EnrolmentInfo(Device device, String owner, OwnerShip ownership, Status status) { public EnrolmentInfo(Device device, String owner, OwnerShip ownership, Status status) {
this.device = device; this.device = device;
@ -109,19 +110,12 @@ public class EnrolmentInfo implements Serializable{
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof EnrolmentInfo) { if (obj instanceof EnrolmentInfo) {
EnrolmentInfo tempInfo = (EnrolmentInfo) obj; EnrolmentInfo tempInfo = (EnrolmentInfo) obj;
if (owner != null && ownership != null if (this.owner != null && this.ownership != null) {
&& tempInfo.getOwner() != null && tempInfo.getOwnership() != null) { if (this.owner.equals(tempInfo.getOwner()) && this.ownership.equals(tempInfo.getOwnership())) {
if (owner.equals(tempInfo.getOwner()) && ownership.equals(tempInfo.getOwnership())) {
return true; return true;
} else {
return false;
} }
} else {
return false;
} }
} else { }
return false; return false;
} }
} }
}

View File

@ -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);
}
}

View File

@ -0,0 +1,93 @@
/*
* 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.notification.mgt;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
/**
* DTO of Notification object which is used to communicate Operation notifications to MDM core.
*/
public class Notification {
public enum Status{
NEW, CHECKED
}
public enum Type{
ALERT,
}
private int notificationId;
private DeviceIdentifier deviceIdentifier;
private String description;
private int operationId;
private Status status;
public Status getStatus() {
return status;
}
public void setStatus(String status) {
this.status = Status.valueOf(status);
}
public int getNotificationId() {
return notificationId;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
}
public DeviceIdentifier getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
@Override
public String toString() {
return "Notification{" +
"notificationId='" + notificationId + '\'' +
", deviceId=" + deviceIdentifier.getId() +
", deviceType=" + deviceIdentifier.getType() +
", status=" + status +
", description='" + description + '\'' +
", operationId='" + operationId + '\'' +
'}';
}
}

View File

@ -0,0 +1,60 @@
/*
* 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.notification.mgt;
/**
* Custom exception class to be used in NotificationMgmt related functionalities.
*/
public class NotificationManagementException extends Exception {
private static final long serialVersionUID = -8933146283800122660L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public NotificationManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public NotificationManagementException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public NotificationManagementException(String msg) {
super(msg);
setErrorMessage(msg);
}
public NotificationManagementException() {
super();
}
public NotificationManagementException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,36 @@
/*
* 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.notification.mgt;
import java.util.List;
/**
* Defines the contract of NotificationManagementService.
*/
public interface NotificationManagementService {
public boolean addNotification(Notification notification) throws NotificationManagementException;
public boolean updateNotification(Notification notification) throws NotificationManagementException;
public boolean updateNotificationStatus(int notificationId, Notification.Status status) throws
NotificationManagementException;
public List<Notification> getAllNotifications() throws NotificationManagementException;
public List<Notification> getNotificationsByStatus(Notification.Status status) throws
NotificationManagementException;
}

View File

@ -45,6 +45,7 @@ import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO; import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -173,6 +174,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
@Override @Override
public void updateApplicationListInstalledInDevice( public void updateApplicationListInstalledInDevice(
DeviceIdentifier deviceIdentifier, List<Application> applications) throws ApplicationManagementException { DeviceIdentifier deviceIdentifier, List<Application> applications) throws ApplicationManagementException {
List<Application> installedAppList = getApplicationListForDevice(deviceIdentifier);
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManagementDAOFactory.beginTransaction(); DeviceManagementDAOFactory.beginTransaction();
@ -182,8 +184,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId()); log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId());
} }
List<Application> installedAppList = getApplicationListForDevice(deviceIdentifier);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("num of apps installed:" + installedAppList.size()); log.debug("num of apps installed:" + installedAppList.size());
} }
@ -227,9 +227,13 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
} }
applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId); applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException | TransactionManagementException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
throw new ApplicationManagementException("Error occurred saving application list to the device", e); 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; Device device;
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceId, tenantId); device = deviceDAO.getDevice(deviceId, tenantId);
return applicationDAO.getInstalledApplications(device.getId()); return applicationDAO.getInstalledApplications(device.getId());
} catch (DeviceManagementDAOException e) { } 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); 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();
} }
} }

View File

@ -36,8 +36,9 @@ import java.io.StringWriter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
/** /**
* This class implements all the functionality exposed as part of the TenantConfigurationManagementService. Main usage of * This class implements all the functionality exposed as part of the TenantConfigurationManagementService.
* this module is, saving/retrieving tenant configurations to the registry. * Main usage of this module is saving/retrieving tenant configurations to the registry.
*
*/ */
public class TenantConfigurationManagementServiceImpl public class TenantConfigurationManagementServiceImpl
implements TenantConfigurationManagementService { implements TenantConfigurationManagementService {

View File

@ -31,38 +31,170 @@ import java.util.List;
*/ */
public interface DeviceDAO { public interface DeviceDAO {
/**
* This method is used to add a device.
*
* @param typeId device type id.
* @param device device object.
* @param tenantId tenant id.
* @return returns the id of the persisted device record.
* @throws DeviceManagementDAOException
*/
int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException; int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to update a given device.
*
* @param typeId device type id.
* @param device device object.
* @param tenantId tenant id.
* @return returns the id of updated device.
* @throws DeviceManagementDAOException
*/
int updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException; int updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to remove a device.
*
* @param deviceId id of the device that should be removed.
* @param tenantId tenant id.
* @return returns the id of removed device.
* @throws DeviceManagementDAOException
*/
int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException;
Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; /**
* This method is used to retrieve a device of a given device-identifier.
*
* @param deviceIdentifier device id.
* @param tenantId tenant id.
* @return returns the device object.
* @throws DeviceManagementDAOException
*/
Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve a device of a given id.
*
* @param deviceId device id.
* @param tenantId tenant id.
* @return returns the device object.
* @throws DeviceManagementDAOException
*/
Device getDevice(int deviceId, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve all the devices of a given tenant.
*
* @param tenantId tenant id.
* @return returns a list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevices(int tenantId) throws DeviceManagementDAOException; List<Device> getDevices(int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve all the devices of a given tenant and device type.
*
* @param type device type.
* @param tenantId tenant id.
* @return returns list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevices(String type, int tenantId) throws DeviceManagementDAOException; List<Device> getDevices(String type, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve devices of a given user.
* @param username user name.
* @param tenantId tenant id.
* @return returns list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException; List<Device> getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the device count of a given tenant.
*
* @param tenantId tenant id.
* @return returns the device count.
* @throws DeviceManagementDAOException
*/
int getDeviceCount(int tenantId) throws DeviceManagementDAOException; int getDeviceCount(int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve devices of a given device name.
* @param deviceName device name.
* @param tenantId tenant id.
* @return returns list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to add an enrollment information of a given device.
*
* @param device device object.
* @param tenantId tenant id.
* @return returns the id of the enrollment.
* @throws DeviceManagementDAOException
*/
int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException; int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to set the current enrollment status of given device and user.
*
* @param deviceId device id.
* @param currentOwner current user name.
* @param status device status.
* @param tenantId tenant id.
* @return returns true if success.
* @throws DeviceManagementDAOException
*/
boolean setEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, Status status, boolean setEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, Status status,
int tenantId) throws DeviceManagementDAOException; int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to get the status of current enrollment of a given user and device.
*
* @param deviceId device id.
* @param currentOwner device owner.
* @param tenantId tenant id.
* @return returns current enrollment status.
* @throws DeviceManagementDAOException
*/
Status getEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, Status getEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException; int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve current enrollment of a given device and user.
*
* @param deviceId device id.
* @param currentUser user name.
* @param tenantId tenant id.
* @return returns EnrolmentInfo object.
* @throws DeviceManagementDAOException
*/
EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser, EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser,
int tenantId) throws DeviceManagementDAOException; int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve devices of a given enrollment status.
*
* @param status enrollment status.
* @param tenantId tenant id.
* @return returns list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesByStatus(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException; List<Device> getDevicesByStatus(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the enrollment id of a given device and status.
*
* @param deviceId device id.
* @param status enrollment status.
* @param tenantId tenant id.
* @return returns the id of current enrollment.
* @throws DeviceManagementDAOException
*/
int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status, int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status,
int tenantId) throws DeviceManagementDAOException; int tenantId) throws DeviceManagementDAOException;
} }

View File

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; 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.config.datasource.JNDILookupDefinition;
@ -113,8 +114,14 @@ public class DeviceManagementDAOFactory {
} }
public static void beginTransaction() throws TransactionManagementException { 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 { try {
Connection conn = dataSource.getConnection(); conn = dataSource.getConnection();
conn.setAutoCommit(false); conn.setAutoCommit(false);
currentConnection.set(conn); currentConnection.set(conn);
} catch (SQLException e) { } catch (SQLException e) {
@ -123,59 +130,68 @@ public class DeviceManagementDAOFactory {
} }
public static void openConnection() throws SQLException { 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 { public static Connection getConnection() throws SQLException {
if (currentConnection.get() == null) { Connection conn = currentConnection.get();
currentConnection.set(dataSource.getConnection()); 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() { public static void commitTransaction() {
try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
if (conn != null) { 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.commit(); conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) { } catch (SQLException e) {
log.error("Error occurred while committing the transaction", e); log.error("Error occurred while committing the transaction", e);
} }
} }
public static void rollbackTransaction() { public static void rollbackTransaction() {
try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
if (conn != null) { 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.rollback(); conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) { } 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() { public static void closeConnection() {
Connection con = currentConnection.get(); Connection conn = currentConnection.get();
if (con != null) { 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 { try {
con.close(); conn.close();
} catch (SQLException e) { } catch (SQLException e) {
log.warn("Error occurred while close the connection"); log.warn("Error occurred while close the connection");
} }
currentConnection.remove(); currentConnection.remove();
} }
}
/** /**

View File

@ -42,8 +42,7 @@ public class DeviceDAOImpl implements DeviceDAO {
int deviceId = -1; int deviceId = -1;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) " +
"INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?)"; "VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, device.getDescription()); stmt.setString(1, device.getDescription());
@ -74,8 +73,7 @@ public class DeviceDAOImpl implements DeviceDAO {
int deviceId = -1; int deviceId = -1;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "UPDATE DM_DEVICE SET DESCRIPTION = ?, NAME = ? WHERE DEVICE_IDENTIFICATION = ? AND " +
"UPDATE DM_DEVICE SET DESCRIPTION = ?, NAME = ? WHERE DEVICE_IDENTIFICATION = ? AND " +
"DEVICE_TYPE_ID = ? AND TENANT_ID = ?"; "DEVICE_TYPE_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, device.getDescription()); stmt.setString(1, device.getDescription());
@ -104,23 +102,22 @@ public class DeviceDAOImpl implements DeviceDAO {
} }
@Override @Override
public Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException { public Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
Device device = null; Device device = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"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 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 " + "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
"AND TENANT_ID = ?"; "AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getType()); stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceId.getId()); stmt.setString(2, deviceIdentifier.getId());
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId); stmt.setInt(4, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
@ -129,7 +126,38 @@ public class DeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while listing devices for type " + throw new DeviceManagementDAOException("Error occurred while listing devices for type " +
"'" + deviceId.getType() + "'", e); "'" + deviceIdentifier.getType() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return device;
}
@Override
public Device getDevice(int deviceId, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
Device device = null;
try {
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.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 " +
"d.ID = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
"AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
device = this.loadDevice(rs);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving device for id " +
"'" + deviceId + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -144,12 +172,12 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = null; List<Device> devices = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " +
"FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME," + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -176,12 +204,12 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = null; List<Device> devices = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " +
"FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "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 = ?"; "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, type); stmt.setString(1, type);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -207,11 +235,10 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"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, " + "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 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.NAME, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "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 d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?"; "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
@ -281,12 +308,12 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DESCRIPTION, t.NAME AS DEVICE_TYPE, " + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " +
"d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " +
"AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceName + "%"); stmt.setString(1, deviceName + "%");
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -314,9 +341,8 @@ public class DeviceDAOImpl implements DeviceDAO {
int enrolmentId = -1; int enrolmentId = -1;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " +
"INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, " + "DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)";
"TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, device.getId()); stmt.setInt(1, device.getId());
stmt.setString(2, device.getEnrolmentInfo().getOwner()); stmt.setString(2, device.getEnrolmentInfo().getOwner());
@ -346,10 +372,9 @@ public class DeviceDAOImpl implements DeviceDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, " +
"UPDATE DM_ENROLMENT SET STATUS = ? WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + "AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?";
"AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString()); stmt.setString(1, status.toString());
stmt.setString(2, deviceId.getId()); stmt.setString(2, deviceId.getId());
@ -375,10 +400,9 @@ public class DeviceDAOImpl implements DeviceDAO {
Status status = null; Status status = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, " +
"SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? " +
"(SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND " + "AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?";
"d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId()); stmt.setString(1, deviceId.getId());
stmt.setString(2, deviceId.getType()); stmt.setString(2, deviceId.getType());
@ -407,10 +431,10 @@ public class DeviceDAOImpl implements DeviceDAO {
EnrolmentInfo enrolmentInfo = null; EnrolmentInfo enrolmentInfo = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " +
"SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, " + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " +
"TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " +
"WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " +
"AND OWNER = ? AND TENANT_ID = ?"; "AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId()); stmt.setString(1, deviceId.getId());
@ -438,10 +462,10 @@ public class DeviceDAOImpl implements DeviceDAO {
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT ID AS ENROLMENT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " +
"SELECT ID AS ENROLMENT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, " + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? " + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " +
"AND d.TENANT_ID = ?) AND STATUS = ? AND TENANT_ID = ?"; "AND STATUS = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId()); stmt.setString(1, deviceId.getId());
stmt.setString(2, deviceId.getType()); stmt.setString(2, deviceId.getType());
@ -491,13 +515,12 @@ public class DeviceDAOImpl implements DeviceDAO {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " +
"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, " + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"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 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 = ? " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " +
"AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_ID = e.DEVICE_ID " + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " +
"AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setString(2, status.toString()); stmt.setString(2, status.toString());
@ -516,4 +539,5 @@ public class DeviceDAOImpl implements DeviceDAO {
} }
return devices; return devices;
} }
} }

View File

@ -25,6 +25,8 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
@ -39,6 +41,7 @@ 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.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl; 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.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; 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.DeviceManagementProviderService;
@ -178,6 +181,11 @@ public class DeviceManagementServiceComponent {
tenantConfiguration = new TenantConfigurationManagementServiceImpl(); tenantConfiguration = new TenantConfigurationManagementServiceImpl();
bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null); bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null);
/* Registering Notification Service */
NotificationManagementService notificationManagementService
= new NotificationManagementServiceImpl();
bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null);
/* Registering App Management service */ /* Registering App Management service */
try { try {
AppManagementConfigurationManager.getInstance().initConfig(); AppManagementConfigurationManager.getInstance().initConfig();

View File

@ -0,0 +1,172 @@
/*
* 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.core.notification.mgt;
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.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
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.notification.mgt.dao.NotificationDAO;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil;
import java.sql.SQLException;
import java.util.List;
/**
* This class implements the NotificationManagementService.
*/
public class NotificationManagementServiceImpl implements NotificationManagementService {
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
private NotificationDAO notificationDAO;
private DeviceDAO deviceDAO;
public NotificationManagementServiceImpl() {
this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
}
@Override
public boolean addNotification(Notification notification) throws NotificationManagementException {
boolean status = false;
int deviceId, tenantId;
if (log.isDebugEnabled()) {
log.debug("Adding a Notification : [" + notification.toString() + "]");
}
try {
tenantId = NotificationDAOUtil.getTenantId();
DeviceManagementDAOFactory.openConnection();
Device device = deviceDAO.getDevice(notification.getDeviceIdentifier(), tenantId);
deviceId = device.getId();
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection to" +
" the data source", e);
} catch (DeviceManagementDAOException e) {
throw new NotificationManagementException("Error occurred while retriving device data for " +
" adding notification", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
try {
NotificationManagementDAOFactory.beginTransaction();
int notificationId = notificationDAO.addNotification(deviceId, tenantId, notification);
NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId +" was added to the table.");
}
if(notificationId > 0) {
status = true;
}
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while adding notification", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return status;
}
@Override
public boolean updateNotification(Notification notification) throws NotificationManagementException {
boolean status = false;
if (log.isDebugEnabled()) {
log.debug("Updating Notification : [" + notification.toString() + "]");
}
try {
NotificationManagementDAOFactory.beginTransaction();
if(notificationDAO.updateNotification(notification) > 0 ) {
status = true;
}
NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notification.getNotificationId() +
" has updated successfully.");
}
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating notification ", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return status;
}
@Override
public boolean updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException {
boolean operationStatus = false;
if (log.isDebugEnabled()) {
log.debug("Updating Notification id : " + notificationId);
}
try {
NotificationManagementDAOFactory.beginTransaction();
if(notificationDAO.updateNotificationStatus(notificationId, status) > 0 ) {
operationStatus = true;
}
NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId +" has updated successfully.");
}
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating notification", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return operationStatus;
}
@Override
public List<Notification> getAllNotifications() throws NotificationManagementException{
try {
NotificationManagementDAOFactory.openConnection();
return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId());
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection to" +
" the data source", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
}
@Override
public List<Notification> getNotificationsByStatus(Notification.Status status)
throws NotificationManagementException{
try {
NotificationManagementDAOFactory.openConnection();
return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId());
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection " +
"to the data source", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
}
}

View File

@ -0,0 +1,83 @@
/*
* 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.core.notification.mgt.dao;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import java.util.List;
/**
* This class defines the methods to be implemented by NotificationDAO layer.
*/
public interface NotificationDAO {
/**
* This method is used to add a notification.
*
* @param deviceId device id.
* @param tenantId tenant id.
* @param notification Notification object.
* @return returns the id of the persisted Notification record.
* @throws NotificationManagementException
*/
int addNotification(int deviceId, int tenantId, Notification notification) throws
NotificationManagementException;
/**
* This method is used to update a notification.
*
* @param notification Notification object.
* @return returns the no of updated records.
* @throws NotificationManagementException
*/
int updateNotification(Notification notification) throws NotificationManagementException;
/**
* This method is used to update a notification status.
*
* @param notificationId notification id.
* @param status Notification.Status.
* @return returns the no of updated records.
* @throws NotificationManagementException
*/
int updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException;
/**
* This method is used to get all notifications based on tenant-id.
*
* @param tenantId tenant id.
* @return returns the matching notifications.
* @throws NotificationManagementException
*/
List<Notification> getAllNotifications(int tenantId) throws NotificationManagementException;
/**
* This method is used to get all notifications based on notification-status.
*
* @param status Notification.Status.
* @param tenantId tenant id.
* @return returns the matching notifications.
* @throws NotificationManagementException
*/
List<Notification> getNotificationsByStatus(Notification.Status status, int tenantId) throws
NotificationManagementException;
}

View File

@ -0,0 +1,171 @@
/*
* 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.core.notification.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;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.NotificationDAOImpl;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
/**
* DAO factory class to be used in NotificationManagement related functionalities.
*/
public class NotificationManagementDAOFactory {
private static DataSource dataSource;
private static final Log log = LogFactory.getLog(NotificationManagementDAOFactory.class);
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public static NotificationDAO getNotificationDAO() {
return new NotificationDAOImpl();
}
public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config);
}
public static void init(DataSource dtSource) {
dataSource = dtSource;
}
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 {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e);
}
}
public static void openConnection() throws SQLException {
Connection conn = currentConnection.get();
if (conn != null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
"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 {
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 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 {
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 {
conn.rollback();
} catch (SQLException e) {
log.warn("Error occurred while roll-backing the transaction", e);
}
}
public static void closeConnection() {
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();
}
/**
* Resolve data source from the data source definition
*
* @param config data source configuration
* @return data source resolved from the data source definition
*/
private static DataSource resolveDataSource(DataSourceConfig config) {
DataSource dataSource = null;
if (config == null) {
throw new RuntimeException(
"Device Management Repository data source configuration " + "is null and " +
"thus, is not initialized");
}
JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition();
if (jndiConfig != null) {
if (log.isDebugEnabled()) {
log.debug("Initializing Device Management Repository data source using the JNDI " +
"Lookup Definition");
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
dataSource = NotificationDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else {
dataSource = NotificationDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null);
}
}
return dataSource;
}
}

View File

@ -0,0 +1,214 @@
/*
* 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.core.notification.mgt.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Implementation of NotificationDAO which includes the methods to do CRUD operations on notification.
*/
public class NotificationDAOImpl implements NotificationDAO {
private static final Log log = LogFactory.getLog(NotificationDAOImpl.class);
@Override
public int addNotification(int deviceId, int tenantId, Notification notification) throws
NotificationManagementException {
Connection conn;
PreparedStatement stmt;
ResultSet rs;
int notificationId = -1;
try {
NotificationManagementDAOFactory.beginTransaction();
conn = NotificationManagementDAOFactory.getConnection();
String sql =
"INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setInt(2, notification.getOperationId());
stmt.setString(3, notification.getStatus().toString());
stmt.setString(4, notification.getDescription());
stmt.setInt(5, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
notificationId = rs.getInt(1);
}
NotificationManagementDAOFactory.commitTransaction();
} catch (Exception e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while adding the " +
"Notification for device id : " + deviceId,
e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return notificationId;
}
@Override
public int updateNotification(Notification notification)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt;
int rows;
try {
NotificationManagementDAOFactory.beginTransaction();
conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " +
"WHERE NOTIFICATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, notification.getOperationId());
stmt.setString(2, notification.getStatus().toString());
stmt.setString(3, notification.getDescription());
stmt.setInt(4, notification.getNotificationId());
rows = stmt.executeUpdate();
NotificationManagementDAOFactory.commitTransaction();
} catch (Exception e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating the " +
"Notification id : " + notification.getNotificationId(), e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return rows;
}
@Override
public int updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt;
int rows;
try {
NotificationManagementDAOFactory.beginTransaction();
conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setInt(2, notificationId);
rows = stmt.executeUpdate();
NotificationManagementDAOFactory.commitTransaction();
} catch (Exception e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating the status of " +
"Notification id : " + notificationId, e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return rows;
}
@Override
public List<Notification> getAllNotifications(int tenantId)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Notification> notifications = null;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql =
"SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," +
" n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " +
"OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " +
"TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " +
"AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
notifications = new ArrayList<>();
while (rs.next()) {
notifications.add(this.getNotification(rs));
}
} catch (SQLException e) {
throw new NotificationManagementException(
"Error occurred while retrieving information of all " +
"notifications", e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
@Override
public List<Notification> getNotificationsByStatus(Notification.Status status, int tenantId)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Notification> notifications = null;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," +
" n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " +
"OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " +
"TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " +
"AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, status.toString());
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
notifications = new ArrayList<>();
while (rs.next()) {
notifications.add(this.getNotification(rs));
}
} catch (SQLException e) {
throw new NotificationManagementException(
"Error occurred while retrieving information of all " +
"notifications by status : " + status, e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
private Notification getNotification(ResultSet rs) throws SQLException {
Notification notification = new Notification();
notification.setNotificationId(rs.getInt("NOTIFICATION_ID"));
notification.setDeviceIdentifier(this.getDeviceIdentifier(rs));
notification.setOperationId(rs.getInt("OPERATION_ID"));
notification.setDescription(rs.getString("DESCRIPTION"));
notification.setStatus(rs.getString("STATUS"));
return notification;
}
private DeviceIdentifier getDeviceIdentifier(ResultSet rs) throws SQLException {
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(rs.getString("DEVICE_IDENTIFICATION"));
identifier.setType(rs.getString("DEVICE_TYPE"));
return identifier;
}
}

View File

@ -0,0 +1,126 @@
/*
* 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.core.notification.mgt.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
/**
* This class includes the utility methods required by NotificationMgmt functionalities.
*/
public class NotificationDAOUtil {
private static final Log log = LogFactory.getLog(NotificationDAOUtil.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
}
/**
* Get id of the current tenant.
*
* @return tenant id
* @throws org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException if an error is observed when getting tenant id
*/
public static int getTenantId() throws NotificationManagementException {
CarbonContext context = CarbonContext.getThreadLocalCarbonContext();
int tenantId = context.getTenantId();
if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
return tenantId;
}
String tenantDomain = context.getTenantDomain();
if (tenantDomain == null) {
String msg = "Tenant domain is not properly set and thus, is null";
throw new NotificationManagementException(msg);
}
TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager();
try {
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
String msg =
"Error occurred while retrieving id from the domain of tenant " + tenantDomain;
throw new NotificationManagementException(msg);
}
return tenantId;
}
public static DataSource lookupDataSource(String dataSourceName,
final Hashtable<Object, Object> jndiProperties) {
try {
if (jndiProperties == null || jndiProperties.isEmpty()) {
return (DataSource) InitialContext.doLookup(dataSourceName);
}
final InitialContext context = new InitialContext(jndiProperties);
return (DataSource) context.lookup(dataSourceName);
} catch (Exception e) {
throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e);
}
}
}

View File

@ -81,6 +81,7 @@ public class OperationManagerImpl implements OperationManager {
} }
try { try {
OperationManagementDAOFactory.beginTransaction(); OperationManagementDAOFactory.beginTransaction();
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
OperationDAOUtil.convertOperation(operation); OperationDAOUtil.convertOperation(operation);
@ -89,7 +90,16 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId; int enrolmentId;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
for (DeviceIdentifier deviceId : deviceIds) { for (DeviceIdentifier deviceId : deviceIds) {
try {
DeviceManagementDAOFactory.openConnection();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); 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) { if (enrolmentId < 0) {
String errorMsg = "The operation not added for device.The device not found for " + String errorMsg = "The operation not added for device.The device not found for " +
"device Identifier type -'" + deviceId.getType() + "' and device Id '" + "device Identifier type -'" + deviceId.getType() + "' and device Id '" +
@ -119,10 +129,15 @@ public class OperationManagerImpl implements OperationManager {
int enrolmentId; int enrolmentId;
List<Operation> operations = new ArrayList<>(); List<Operation> operations = new ArrayList<>();
try { try {
OperationManagementDAOFactory.openConnection(); try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) { if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device " + throw new OperationManagementException("Device not found for given device " +
@ -160,11 +175,17 @@ public class OperationManagerImpl implements OperationManager {
List<Operation> operations = new ArrayList<>(); List<Operation> operations = new ArrayList<>();
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>(); List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();
try { try {
OperationManagementDAOFactory.openConnection();
try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) { if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for the given device Identifier:" + 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());
@ -213,10 +234,15 @@ public class OperationManagerImpl implements OperationManager {
Operation operation = null; Operation operation = null;
int enrolmentId; int enrolmentId;
try { try {
OperationManagementDAOFactory.openConnection(); try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) { if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device " + throw new OperationManagementException("Device not found for given device " +
@ -264,11 +290,19 @@ public class OperationManagerImpl implements OperationManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("operation Id:" + operationId + " status:" + operation.getStatus()); log.debug("operation Id:" + operationId + " status:" + operation.getStatus());
} }
int enrolmentId;
try { try {
OperationManagementDAOFactory.beginTransaction(); try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
int enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); 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();
}
OperationManagementDAOFactory.beginTransaction();
if (operation.getStatus() != null) { if (operation.getStatus() != null) {
operationDAO.updateOperationStatus(enrolmentId, operationId, operationDAO.updateOperationStatus(enrolmentId, operationId,
@ -327,10 +361,16 @@ public class OperationManagerImpl implements OperationManager {
deviceId.getId()); deviceId.getId());
} }
try { try {
OperationManagementDAOFactory.openConnection(); try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) { if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for given device identifier:" + throw new OperationManagementException("Device not found for given device identifier:" +
deviceId.getId() + " type:" + deviceId.getType()); deviceId.getId() + " type:" + deviceId.getType());
@ -383,11 +423,16 @@ public class OperationManagerImpl implements OperationManager {
List<Operation> operations = new ArrayList<>(); List<Operation> operations = new ArrayList<>();
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList =
new ArrayList<>(); new ArrayList<>();
int enrolmentId;
try { try {
OperationManagementDAOFactory.openConnection(); try {
DeviceManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
int enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
OperationManagementDAOFactory.openConnection();
if (enrolmentId < 0) { if (enrolmentId < 0) {
throw new OperationManagementException("Device not found for device id:" + deviceId.getId() + " " + throw new OperationManagementException("Device not found for device id:" + deviceId.getId() + " " +

View File

@ -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.Log;
import org.apache.commons.logging.LogFactory; 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.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; 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.config.datasource.JNDILookupDefinition;
@ -87,7 +88,9 @@ public class OperationManagementDAOFactory {
public static Connection getConnection() throws SQLException { public static Connection getConnection() throws SQLException {
if (currentConnection.get() == null) { 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(); return currentConnection.get();
} }

View File

@ -120,9 +120,11 @@ public class CommandOperationDAOImpl extends OperationDAOImpl {
List<CommandOperation> commandOperations = new ArrayList<>(); List<CommandOperation> commandOperations = new ArrayList<>();
try { try {
Connection conn = OperationManagementDAOFactory.getConnection(); Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, co1.ENABLED, co1.STATUS, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE FROM (SELECT co.OPERATION_ID, co.ENABLED, dm.STATUS FROM DM_COMMAND_OPERATION co " + String sql = "SELECT o.ID, co1.ENABLED, co1.STATUS, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"INNER JOIN (SELECT ENROLMENT_ID, OPERATION_ID, STATUS FROM DM_ENROLMENT_OPERATION_MAPPING WHERE ENROLMENT_ID = ? " + "o.OPERATION_CODE FROM (SELECT co.OPERATION_ID, co.ENABLED, dm.STATUS " +
"AND STATUS = ?) dm ON dm.OPERATION_ID = co.OPERATION_ID) co1 INNER JOIN DM_OPERATION o ON co1.OPERATION_ID = o.ID"; "FROM DM_COMMAND_OPERATION co INNER JOIN (SELECT ENROLMENT_ID, OPERATION_ID, STATUS " +
"FROM DM_ENROLMENT_OPERATION_MAPPING WHERE ENROLMENT_ID = ? AND STATUS = ?) dm " +
"ON dm.OPERATION_ID = co.OPERATION_ID) co1 INNER JOIN DM_OPERATION o ON co1.OPERATION_ID = o.ID";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId); stmt.setInt(1, enrolmentId);

View File

@ -93,7 +93,7 @@ public interface DeviceManagementProviderService extends OperationManager {
void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException; void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException;
/** /**
* This method is used to retrieve list of devices based on the device status * This method is used to retrieve list of devices based on the device status.
* *
* @param status Device status * @param status Device status
* @return List of devices * @return List of devices

View File

@ -156,9 +156,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
device.getDeviceIdentifier() + "', which belongs to " + "platform '" + device.getDeviceIdentifier() + "', which belongs to " + "platform '" +
device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'"); device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'");
} }
} catch (TransactionManagementException | DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); 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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -173,10 +175,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId); int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId);
enrolmentId = enrolmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); enrolmentId = enrolmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException | TransactionManagementException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
log.error("Error occurred while adding metadata of '" + device.getType() + "' device carrying " + throw new DeviceManagementException("Error occurred while adding metadata of '" + device.getType() +
"the identifier '" + device.getDeviceIdentifier() + "'", e); "' device carrying the identifier '" + device.getDeviceIdentifier() + "'", e);
} catch (TransactionManagementException e) {
throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -214,10 +218,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
enrolmentDAO.updateEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); enrolmentDAO.updateEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException | TransactionManagementException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while modifying the device " + throw new DeviceManagementException("Error occurred while modifying the device " +
"'" + device.getId() + "'", e); "'" + device.getId() + "'", e);
} catch (TransactionManagementException e) {
throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -247,10 +253,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceDAO.updateDevice(deviceType.getId(), device, tenantId); deviceDAO.updateDevice(deviceType.getId(), device, tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException | TransactionManagementException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while dis-enrolling '" + deviceId.getType() + throw new DeviceManagementException("Error occurred while dis-enrolling '" + deviceId.getType() +
"' device with the identifier '" + deviceId.getId() + "'", e); "' device with the identifier '" + deviceId.getId() + "'", e);
} catch (TransactionManagementException e) {
throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -302,14 +310,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
List<Device> allDevices; List<Device> allDevices;
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevices(this.getTenantId()); allDevices = deviceDAO.getDevices(this.getTenantId());
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " + throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " +
"the current tenant", e); "the current tenant", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
for (Device device : allDevices) { for (Device device : allDevices) {
DeviceManager deviceManager = this.getDeviceManager(device.getType()); DeviceManager deviceManager = this.getDeviceManager(device.getType());
if (deviceManager == null) { if (deviceManager == null) {
@ -338,9 +348,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevices(deviceType, this.getTenantId()); allDevices = deviceDAO.getDevices(deviceType, this.getTenantId());
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving all devices of type '" + throw new DeviceManagementException("Error occurred while retrieving all devices of type '" +
deviceType + "' that are being managed within the scope of current tenant", e); 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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -415,7 +427,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
.getProperty("line.separator")).append(messageFooter3.trim()); .getProperty("line.separator")).append(messageFooter3.trim());
} catch (IOException e) { } catch (IOException e) {
log.error("IO error in processing enrol email message " + emailMessageProperties);
throw new DeviceManagementException("Error replacing tags in email template '" + throw new DeviceManagementException("Error replacing tags in email template '" +
emailMessageProperties.getSubject() + "'", e); emailMessageProperties.getSubject() + "'", e);
} }
@ -479,7 +490,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
messageBuilder.append(System.getProperty("line.separator")).append(messageFooter3.trim()); messageBuilder.append(System.getProperty("line.separator")).append(messageFooter3.trim());
} catch (IOException e) { } catch (IOException e) {
log.error("IO error in processing enrol email message " + emailMessageProperties);
throw new DeviceManagementException("Error replacing tags in email template '" + throw new DeviceManagementException("Error replacing tags in email template '" +
emailMessageProperties.getSubject() + "'", e); emailMessageProperties.getSubject() + "'", e);
} }
@ -498,8 +508,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
throw new DeviceManagementException("Error occurred while obtaining the device for id " + throw new DeviceManagementException("Error occurred while obtaining the device for id " +
"'" + deviceId.getId() + "'", e); "'" + deviceId.getId() + "'", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementException("Error occurred while obtaining the device for id " + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
"'" + deviceId.getId() + "'", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -574,9 +583,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
return success; return success;
} catch (DeviceManagementDAOException | TransactionManagementException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while setting enrollment status", e); throw new DeviceManagementException("Error occurred while setting enrollment status", e);
} catch (TransactionManagementException e) {
throw new DeviceManagementException("Error occurred while initiating transaction", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -623,8 +634,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
public int addOperation(Operation operation, List<DeviceIdentifier> devices) throws public int addOperation(Operation operation,
OperationManagementException { List<DeviceIdentifier> devices) throws OperationManagementException {
return DeviceManagementDataHolder.getInstance().getOperationManager().addOperation(operation, devices); return DeviceManagementDataHolder.getInstance().getOperationManager().addOperation(operation, devices);
} }
@ -655,8 +666,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId) public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId,
throws OperationManagementException { int operationId) throws OperationManagementException {
return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByDeviceAndOperationId( return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByDeviceAndOperationId(
deviceId, operationId); deviceId, operationId);
} }
@ -681,9 +692,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
userDevices = deviceDAO.getDevicesOfUser(username, this.getTenantId()); 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 " + throw new DeviceManagementException("Error occurred while retrieving the list of devices that " +
"belong to the user '" + username + "'", e); "belong to the user '" + username + "'", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -735,10 +748,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
for (Device device : userDevices) { for (Device device : userDevices) {
Device dmsDevice = Device dmsDevice = this.getDeviceManager(device.getType()).
this.getPluginRepository().getDeviceManagementService( getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
if (dmsDevice != null) { if (dmsDevice != null) {
device.setFeatures(dmsDevice.getFeatures()); device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties()); device.setProperties(dmsDevice.getProperties());
@ -754,8 +765,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDeviceCount(this.getTenantId()); return deviceDAO.getDeviceCount(this.getTenantId());
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the device count", 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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -768,17 +781,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesByName(deviceName, this.getTenantId()); 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 '" throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '"
+ deviceName + "'", e); + deviceName + "'", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
for (Device device : allDevices) { for (Device device : allDevices) {
Device dmsDevice = Device dmsDevice = this.getDeviceManager(device.getType()).
this.getPluginRepository().getDeviceManagementService( getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
if (dmsDevice != null) { if (dmsDevice != null) {
device.setFeatures(dmsDevice.getFeatures()); device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties()); device.setProperties(dmsDevice.getProperties());
@ -792,14 +805,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override @Override
public void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status status) throws DeviceManagementException { public void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status status) throws DeviceManagementException {
try { try {
DeviceManagementDAOFactory.beginTransaction();
DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType()); DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType());
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.getEnrolmentInfo().setStatus(status); device.getEnrolmentInfo().setStatus(status);
deviceDAO.updateDevice(deviceType.getId(), device, this.getTenantId()); deviceDAO.updateDevice(deviceType.getId(), device, this.getTenantId());
} catch (DeviceManagementDAOException deviceDaoEx) {
String errorMsg = "Error occured update device enrolment status : " + device.getId(); DeviceManagementDAOFactory.commitTransaction();
log.error(errorMsg, deviceDaoEx); } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException(errorMsg, deviceDaoEx); 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();
} }
} }
@ -830,19 +851,18 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesByStatus(status, this.getTenantId()); allDevices = deviceDAO.getDevicesByStatus(status, this.getTenantId());
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException( throw new DeviceManagementException(
"Error occurred while fetching the list of devices that matches to status: '" + status + "'", e); "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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
for (Device device : allDevices) { for (Device device : allDevices) {
Device dmsDevice = Device dmsDevice = this.getDeviceManager(device.getType()).
this.getPluginRepository().getDeviceManagementService( getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
device.getType()).getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
if (dmsDevice != null) { if (dmsDevice != null) {
device.setFeatures(dmsDevice.getFeatures()); device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties()); device.setProperties(dmsDevice.getProperties());

View File

@ -23,6 +23,7 @@ import org.w3c.dom.Document;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; 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.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File; import java.io.File;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
@ -97,6 +99,7 @@ public final class DeviceManagerUtil {
public static boolean registerDeviceType(String typeName) throws DeviceManagementException { public static boolean registerDeviceType(String typeName) throws DeviceManagementException {
boolean status; boolean status;
try { try {
DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName); DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName);
if (deviceType == null) { if (deviceType == null) {
@ -104,10 +107,18 @@ public final class DeviceManagerUtil {
dt.setName(typeName); dt.setName(typeName);
deviceTypeDAO.addDeviceType(dt); deviceTypeDAO.addDeviceType(dt);
} }
DeviceManagementDAOFactory.commitTransaction();
status = true; status = true;
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '" + throw new DeviceManagementException("Error occurred while registering the device type '" +
typeName + "'", e); typeName + "'", e);
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("SQL occurred while registering the device type '" +
typeName + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
} }
return status; return status;
} }
@ -120,6 +131,7 @@ public final class DeviceManagerUtil {
*/ */
public static boolean unregisterDeviceType(String typeName) throws DeviceManagementException { public static boolean unregisterDeviceType(String typeName) throws DeviceManagementException {
try { try {
DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName); DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName);
if (deviceType != null) { if (deviceType != null) {
@ -127,10 +139,18 @@ public final class DeviceManagerUtil {
dt.setName(typeName); dt.setName(typeName);
deviceTypeDAO.removeDeviceType(typeName); deviceTypeDAO.removeDeviceType(typeName);
} }
DeviceManagementDAOFactory.commitTransaction();
return true; return true;
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '" + throw new DeviceManagementException("Error occurred while registering the device type '" +
typeName + "'", e); typeName + "'", e);
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("SQL occurred while registering the device type '" +
typeName + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
} }
} }

View File

@ -42,7 +42,8 @@ public class ApplicationManagementProviderServiceTest {
@BeforeClass @BeforeClass
public void init() { public void init() {
deviceManagementPluginRepository = new DeviceManagementPluginRepository(); deviceManagementPluginRepository = new DeviceManagementPluginRepository();
TestDeviceManagementService testDeviceManagementService = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE); TestDeviceManagementService testDeviceManagementService =
new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE);
try { try {
deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService); deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
@ -55,7 +56,7 @@ public class ApplicationManagementProviderServiceTest {
@Test @Test
public void updateApplicationTest() { public void updateApplicationTest() {
List<Application> applications = new ArrayList<Application>(); List<Application> 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 application2 = TestDataHolder.generateApplicationDummyData("org.wso2.app2");
@ -68,15 +69,24 @@ public class ApplicationManagementProviderServiceTest {
applications.add(application4); applications.add(application4);
Device device = TestDataHolder.initialTestDevice; Device device = TestDataHolder.initialTestDevice;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier); if (device == null) {
deviceIdentifier.setType(device.getType()); 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(); AppManagementConfig appManagementConfig = new AppManagementConfig();
appMgtProvider = new ApplicationManagerProviderServiceImpl(deviceManagementPluginRepository); appMgtProvider = new ApplicationManagerProviderServiceImpl(deviceManagementPluginRepository);
try { try {
appMgtProvider.updateApplicationListInstalledInDevice(deviceIdentifier, applications); appMgtProvider.updateApplicationListInstalledInDevice(deviceId, applications);
} catch (ApplicationManagementException appMgtEx) { } catch (ApplicationManagementException appMgtEx) {
String msg = "Error occurred while updating app list '" + TestDataHolder.TEST_DEVICE_TYPE + "'"; String msg = "Error occurred while updating app list '" + TestDataHolder.TEST_DEVICE_TYPE + "'";
log.error(msg, appMgtEx); log.error(msg, appMgtEx);
@ -84,14 +94,14 @@ public class ApplicationManagementProviderServiceTest {
} }
Application application5 = TestDataHolder.generateApplicationDummyData("org.wso2.app5"); Application application5 = TestDataHolder.generateApplicationDummyData("org.wso2.app5");
applications = new ArrayList<Application>(); applications = new ArrayList<>();
applications.add(application4); applications.add(application4);
applications.add(application3); applications.add(application3);
applications.add(application5); applications.add(application5);
try { try {
appMgtProvider.updateApplicationListInstalledInDevice(deviceIdentifier, applications); appMgtProvider.updateApplicationListInstalledInDevice(deviceId, applications);
List<Application> installedApps = appMgtProvider.getApplicationListForDevice(deviceIdentifier); List<Application> installedApps = appMgtProvider.getApplicationListForDevice(deviceId);
log.info("Number of installed applications:" + installedApps.size()); log.info("Number of installed applications:" + installedApps.size());
Assert.assertEquals(installedApps.size(), 3, "Num of installed applications should be two"); Assert.assertEquals(installedApps.size(), 3, "Num of installed applications should be two");
} catch (ApplicationManagementException appMgtEx) { } catch (ApplicationManagementException appMgtEx) {

View File

@ -129,11 +129,12 @@ public abstract class BaseDeviceManagementTest {
conn = getDataSource().getConnection(); conn = getDataSource().getConnection();
conn.setAutoCommit(false); conn.setAutoCommit(false);
this.cleanupEnrolmentData(conn); //TODO:FIX ME
this.cleanApplicationMappingData(conn); // this.cleanupEnrolmentData(conn);
this.cleanApplicationData(conn); // this.cleanApplicationMappingData(conn);
this.cleanupDeviceData(conn); // this.cleanApplicationData(conn);
this.cleanupDeviceTypeData(conn); // this.cleanupDeviceData(conn);
// this.cleanupDeviceTypeData(conn);
conn.commit(); conn.commit();
} catch (SQLException e) { } catch (SQLException e) {
@ -159,63 +160,33 @@ public abstract class BaseDeviceManagementTest {
} }
private void cleanApplicationMappingData(Connection conn) throws SQLException { private void cleanApplicationMappingData(Connection conn) throws SQLException {
PreparedStatement stmt = null; try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_APPLICATION_MAPPING")) {
try {
stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_APPLICATION_MAPPING");
stmt.execute(); stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
} }
} }
private void cleanApplicationData(Connection conn) throws SQLException { private void cleanApplicationData(Connection conn) throws SQLException {
PreparedStatement stmt = null; try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_APPLICATION")) {
try {
stmt = conn.prepareStatement("DELETE FROM DM_APPLICATION");
stmt.execute(); stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
} }
} }
private void cleanupEnrolmentData(Connection conn) throws SQLException { private void cleanupEnrolmentData(Connection conn) throws SQLException {
PreparedStatement stmt = null; try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT")) {
try {
stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT");
stmt.execute(); stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
} }
} }
private void cleanupDeviceData(Connection conn) throws SQLException { private void cleanupDeviceData(Connection conn) throws SQLException {
PreparedStatement stmt = null; try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE")) {
try {
stmt = conn.prepareStatement("DELETE FROM DM_DEVICE");
stmt.execute(); stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
} }
} }
private void cleanupDeviceTypeData(Connection conn) throws SQLException { private void cleanupDeviceTypeData(Connection conn) throws SQLException {
PreparedStatement stmt = null; try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE")) {
try {
stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE");
stmt.execute(); stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
} }
} }

View File

@ -26,6 +26,7 @@ import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status; 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.TestUtils;
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder; import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
@ -50,12 +51,18 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
public void testAddDeviceTypeTest() { public void testAddDeviceTypeTest() {
DeviceType deviceType = TestDataHolder.generateDeviceTypeData(TestDataHolder.TEST_DEVICE_TYPE); DeviceType deviceType = TestDataHolder.generateDeviceTypeData(TestDataHolder.TEST_DEVICE_TYPE);
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.beginTransaction();
deviceTypeDAO.addDeviceType(deviceType); deviceTypeDAO.addDeviceType(deviceType);
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while adding device type '" + deviceType.getName() + "'"; String msg = "Error occurred while adding device type '" + deviceType.getName() + "'";
log.error(msg, e); log.error(msg, e);
Assert.fail(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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -75,21 +82,26 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
@Test(dependsOnMethods = {"testAddDeviceTypeTest"}) @Test(dependsOnMethods = {"testAddDeviceTypeTest"})
public void testAddDeviceTest() { public void testAddDeviceTest() {
int tenantId = TestDataHolder.SUPER_TENANT_ID; int tenantId = TestDataHolder.SUPER_TENANT_ID;
Device device = TestDataHolder.generateDummyDeviceData(TestDataHolder.TEST_DEVICE_TYPE); Device device = TestDataHolder.generateDummyDeviceData(TestDataHolder.TEST_DEVICE_TYPE);
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.beginTransaction();
int deviceId = deviceDAO.addDevice(TestDataHolder.initialTestDeviceType.getId(), device, tenantId); int deviceId = deviceDAO.addDevice(TestDataHolder.initialTestDeviceType.getId(), device, tenantId);
device.setId(deviceId); device.setId(deviceId);
deviceDAO.addEnrollment(device, tenantId); deviceDAO.addEnrollment(device, tenantId);
DeviceManagementDAOFactory.commitTransaction();
TestDataHolder.initialTestDevice = device; TestDataHolder.initialTestDevice = device;
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while adding '" + device.getType() + "' device with the identifier '" + String msg = "Error occurred while adding '" + device.getType() + "' device with the identifier '" +
device.getDeviceIdentifier() + "'"; device.getDeviceIdentifier() + "'";
log.error(msg, e); log.error(msg, e);
Assert.fail(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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -164,14 +176,19 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
Device device = TestDataHolder.initialTestDevice; Device device = TestDataHolder.initialTestDevice;
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.beginTransaction();
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()); DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
deviceDAO.setEnrolmentStatus(deviceId, device.getEnrolmentInfo().getOwner(), Status.ACTIVE, deviceDAO.setEnrolmentStatus(deviceId, device.getEnrolmentInfo().getOwner(), Status.ACTIVE,
TestDataHolder.SUPER_TENANT_ID); TestDataHolder.SUPER_TENANT_ID);
} catch (DeviceManagementDAOException | SQLException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while setting enrolment status"; String msg = "Error occurred while setting enrolment status";
log.error(msg, e); log.error(msg, e);
Assert.fail(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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }

View File

@ -128,6 +128,10 @@ public class DynamicClientRegistrationUtil {
serviceProvider.setDescription("Service Provider for application " + applicationName); serviceProvider.setDescription("Service Provider for application " + applicationName);
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
if (appMgtService == null) {
throw new IllegalStateException("Error occurred while retrieving Application Management" +
"Service");
}
appMgtService.createApplication(serviceProvider); appMgtService.createApplication(serviceProvider);
ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName);
@ -228,6 +232,11 @@ public class DynamicClientRegistrationUtil {
oAuthAdminService.removeOAuthApplicationData(consumerKey); oAuthAdminService.removeOAuthApplicationData(consumerKey);
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
if (appMgtService == null) {
throw new IllegalStateException("Error occurred while retrieving Application Management" +
"Service");
}
ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName);
if (createdServiceProvider == null) { if (createdServiceProvider == null) {

View File

@ -45,9 +45,24 @@ public interface RegistrationService {
} }
} }
/**
* This method is used to register an Oauth application.
*
* @param profile contains the necessary attributes that are
* needed in order to register an app.
* @return Status 200 if success including consumerKey and consumerSecret.
*/
@POST @POST
Response register(RegistrationProfile profile); Response register(RegistrationProfile profile);
/**
* This method is used to remove already registered Oauth application.
*
* @param applicationName name of the application.
* @param userId name of the application owner.
* @param consumerKey provided consumerKey for the registered application.
* @return Status 200 if success.
*/
@DELETE @DELETE
public Response unregister(@QueryParam("applicationName") String applicationName, public Response unregister(@QueryParam("applicationName") String applicationName,
@QueryParam("userId") String userId, @QueryParam("userId") String userId,

View File

@ -164,6 +164,4 @@ public class RegistrationProfile {
public void setGrantType(String grantType) { public void setGrantType(String grantType) {
this.grantType = grantType; this.grantType = grantType;
} }
} }

View File

@ -28,6 +28,7 @@ public class ComplianceData {
private int id; private int id;
private int deviceId; private int deviceId;
private int enrolmentId;
private int policyId; private int policyId;
List<ComplianceFeature> complianceFeatures; List<ComplianceFeature> complianceFeatures;
private boolean status; private boolean status;
@ -52,6 +53,14 @@ public class ComplianceData {
this.id = id; this.id = id;
} }
public int getEnrolmentId() {
return enrolmentId;
}
public void setEnrolmentId(int enrolmentId) {
this.enrolmentId = enrolmentId;
}
public Timestamp getLastRequestedTime() { public Timestamp getLastRequestedTime() {
return lastRequestedTime; return lastRequestedTime;
} }

View File

@ -0,0 +1,51 @@
/*
* 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.common.monitor;
public class PolicyDeviceWrapper {
private int policyId;
private int deviceId;
private int enrolmentId;
public int getPolicyId() {
return policyId;
}
public void setPolicyId(int policyId) {
this.policyId = policyId;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public int getEnrolmentId() {
return enrolmentId;
}
public void setEnrolmentId(int enrolmentId) {
this.enrolmentId = enrolmentId;
}
}

View File

@ -71,7 +71,8 @@
org.wso2.carbon.user.api.*, org.wso2.carbon.user.api.*,
org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.device.mgt.core.*,
org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.ntask.* org.wso2.carbon.ntask.*,
org.wso2.carbon.caching.*
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.policy.mgt.core.internal, !org.wso2.carbon.policy.mgt.core.internal,

View File

@ -21,26 +21,28 @@ package org.wso2.carbon.policy.mgt.core.cache.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; 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.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.util.ArrayList; import javax.cache.Cache;
import java.util.HashMap; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set;
public class PolicyCacheManagerImpl implements PolicyCacheManager { public class PolicyCacheManagerImpl implements PolicyCacheManager {
private static final Log log = LogFactory.getLog(PolicyCacheManagerImpl.class); private static final Log log = LogFactory.getLog(PolicyCacheManagerImpl.class);
private static HashMap<Integer, HashMap<Integer, Policy>> tenantedPolicyMap = new HashMap<>();
private static PolicyCacheManagerImpl policyCacheManager; private static PolicyCacheManagerImpl policyCacheManager;
private static Cache<Integer, List<Policy>> getPolicyListCache() {
return PolicyManagerUtil.getPolicyListCache(PolicyManagementConstants.DM_CACHE_LIST);
}
private PolicyCacheManagerImpl() { private PolicyCacheManagerImpl() {
} }
@ -57,43 +59,36 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
@Override @Override
public void addAllPolicies(List<Policy> policies) { public void addAllPolicies(List<Policy> policies) {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (map.isEmpty()) {
for (Policy policy : policies) {
map.put(policy.getId(), policy);
}
}
Cache<Integer, List<Policy>> lCache = getPolicyListCache();
lCache.put(1, policies);
} }
@Override @Override
public void updateAllPolicies(List<Policy> policies) { public void updateAllPolicies(List<Policy> policies) {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
map.clear(); Cache<Integer, List<Policy>> lCache = getPolicyListCache();
if (map.isEmpty()) { lCache.removeAll();
for (Policy policy : policies) { lCache.put(1, policies);
map.put(policy.getId(), policy);
}
}
} }
@Override @Override
public List<Policy> getAllPolicies() throws PolicyManagementException { public List<Policy> getAllPolicies() throws PolicyManagementException {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (map.isEmpty()) { Cache<Integer, List<Policy>> lCache = getPolicyListCache();
if (!lCache.containsKey(1)) {
PolicyManager policyManager = new PolicyManagerImpl(); PolicyManager policyManager = new PolicyManagerImpl();
this.addAllPolicies(policyManager.getPolicies()); this.addAllPolicies(policyManager.getPolicies());
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("No of policies stored in the cache .. : " + map.size()); List<Policy> cachedPolicy = lCache.get(1);
for (Policy policy : cachedPolicy) {
log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy.
getPolicyName() + " Activated : " + policy.isActive());
}
}
return lCache.get(1);
Set<Integer> 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 @Override
@ -105,59 +100,97 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
@Override @Override
public void removeAllPolicies() { public void removeAllPolicies() {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
map.clear(); Cache<Integer, List<Policy>> lCache = getPolicyListCache();
lCache.removeAll();
} }
@Override @Override
public void addPolicy(Policy policy) { public void addPolicy(Policy policy) {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (!map.containsKey(policy.getId())) { Cache<Integer, List<Policy>> lCache = getPolicyListCache();
map.put(policy.getId(), policy); if (lCache.containsKey(1)) {
} else { List<Policy> cachedPolicy = lCache.get(1);
log.warn("Policy id (" + policy.getId() + ") already exist in the map. hence not attempted to store.");
for (Policy pol : cachedPolicy) {
if (pol.getId() == policy.getId()) {
return;
} }
} }
cachedPolicy.add(policy);
}
}
@Override @Override
public void updatePolicy(Policy policy) { public void updatePolicy(Policy policy) {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (map.containsKey(policy.getId())) { Cache<Integer, List<Policy>> lCache = getPolicyListCache();
map.remove(policy.getId()); if (lCache.containsKey(1)) {
map.put(policy.getId(), policy); List<Policy> cachedPolicy = lCache.get(1);
Iterator iterator = cachedPolicy.iterator();
while (iterator.hasNext()) {
Policy pol = (Policy) iterator.next();
if (pol.getId() == policy.getId()) {
iterator.remove();
break;
} }
} }
cachedPolicy.add(policy);
lCache.replace(1, cachedPolicy);
}
}
@Override @Override
public void updatePolicy(int policyId) throws PolicyManagementException { public void updatePolicy(int policyId) throws PolicyManagementException {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (map.containsKey(policyId)) { Cache<Integer, List<Policy>> lCache = getPolicyListCache();
this.removePolicy(policyId); if (lCache.containsKey(1)) {
}
PolicyManager policyManager = new PolicyManagerImpl(); PolicyManager policyManager = new PolicyManagerImpl();
Policy policy = policyManager.getPolicy(policyId); Policy policy = policyManager.getPolicy(policyId);
map.put(policyId, policy); this.updatePolicy(policy);
}
} }
@Override @Override
public void removePolicy(int policyId) { public void removePolicy(int policyId) {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (map.containsKey(policyId)) { Cache<Integer, List<Policy>> lCache = getPolicyListCache();
map.remove(policyId); if (lCache.containsKey(1)) {
} else { List<Policy> cachedPolicy = lCache.get(1);
log.warn("Policy id (" + policyId + ") does not exist in the cache. Hence not removed."); Iterator iterator = cachedPolicy.iterator();
while (iterator.hasNext()) {
Policy pol = (Policy) iterator.next();
if (pol.getId() == policyId) {
iterator.remove();
break;
}
}
lCache.replace(1, cachedPolicy);
} }
} }
@Override @Override
public Policy getPolicy(int policyId) throws PolicyManagementException { public Policy getPolicy(int policyId) throws PolicyManagementException {
HashMap<Integer, Policy> map = this.getTenantRelatedMap();
if (!map.containsKey(policyId)) { Cache<Integer, List<Policy>> lCache = getPolicyListCache();
if (!lCache.containsKey(1)) {
this.removeAllPolicies(); this.removeAllPolicies();
this.getAllPolicies(); this.getAllPolicies();
} }
return map.get(policyId);
Policy policy = null;
List<Policy> cachedPolicy = lCache.get(1);
Iterator iterator = cachedPolicy.iterator();
while (iterator.hasNext()) {
Policy pol = (Policy) iterator.next();
if (pol.getId() == policyId) {
policy = pol;
}
}
return policy;
} }
@Override @Override
@ -175,13 +208,4 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
return 0; return 0;
} }
private HashMap<Integer, Policy> getTenantRelatedMap(){
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if(!tenantedPolicyMap.containsKey(tenantId)){
HashMap<Integer, Policy> policyMap = new HashMap<>();
tenantedPolicyMap.put(tenantId, policyMap);
}
return tenantedPolicyMap.get(tenantId);
}
} }

View File

@ -25,34 +25,102 @@ import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.List; import java.util.List;
/**
* This interface represents the key operations related to profile features of device policies.
*/
public interface FeatureDAO { public interface FeatureDAO {
/* Feature addFeature(Feature feature) throws FeatureManagerDAOException; /**
* This method is used to add a feature related to given profile.
List<Feature> addFeatures(List<Feature> feature) throws FeatureManagerDAOException; *
* @param feature consists of device specific configurations.
Feature updateFeature(Feature feature) throws FeatureManagerDAOException;*/ * @param profileId id of the profile.
* @return returns ProfileFeature object.
* @throws FeatureManagerDAOException
*/
ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException; ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException;
/**
* This method is used to update a feature related to given profile.
* @param feature consists of device specific configurations.
* @param profileId id of the profile.
* @return returns updated ProfileFeature object.
* @throws FeatureManagerDAOException
*/
ProfileFeature updateProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException; ProfileFeature updateProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException;
/**
* This method is used to add set of features to a given profile.
*
* @param features consists of device specific configurations.
* @param profileId id of the profile.
* @return returns list of ProfileFeature objects.
* @throws FeatureManagerDAOException
*/
List<ProfileFeature> addProfileFeatures(List<ProfileFeature> features, int profileId) throws List<ProfileFeature> addProfileFeatures(List<ProfileFeature> features, int profileId) throws
FeatureManagerDAOException; FeatureManagerDAOException;
/**
* This method is used to update set of features to a given profile.
*
* @param features consists of device specific configurations.
* @param profileId id of the profile.
* @return returns list of ProfileFeature objects.
* @throws FeatureManagerDAOException
*/
List<ProfileFeature> updateProfileFeatures(List<ProfileFeature> features, int profileId) throws List<ProfileFeature> updateProfileFeatures(List<ProfileFeature> features, int profileId) throws
FeatureManagerDAOException; FeatureManagerDAOException;
/**
* This method is used to retrieve all the profile features.
*
* @return returns list of ProfileFeature objects.
* @throws FeatureManagerDAOException
*/
List<ProfileFeature> getAllProfileFeatures() throws FeatureManagerDAOException; List<ProfileFeature> getAllProfileFeatures() throws FeatureManagerDAOException;
/**
* This method is used to retrieve all the profile features based on device type.
*
* @return returns list of ProfileFeature objects.
* @throws FeatureManagerDAOException
*/
List<Feature> getAllFeatures(String deviceType) throws FeatureManagerDAOException; List<Feature> getAllFeatures(String deviceType) throws FeatureManagerDAOException;
List<ProfileFeature> getFeaturesForProfile(int ProfileId) throws FeatureManagerDAOException; /**
* This method is used to retrieve all the profile features of given profile.
*
* @param profileId id of the profile.
* @return returns list of ProfileFeature objects.
* @throws FeatureManagerDAOException
*/
List<ProfileFeature> getFeaturesForProfile(int profileId) throws FeatureManagerDAOException;
/**
* This method is used remove a feature.
*
* @param featureId id of the removing feature.
* @return returns true if success.
* @throws FeatureManagerDAOException
*/
boolean deleteFeature(int featureId) throws FeatureManagerDAOException; boolean deleteFeature(int featureId) throws FeatureManagerDAOException;
/**
* This method is used to remove set of features of given profile.
*
* @param profile that contains features to be removed.
* @return returns true if success.
* @throws FeatureManagerDAOException
*/
boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagerDAOException; boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagerDAOException;
/**
* This method is used to remove set of features of given profile id.
*
* @param profileId id of the profile.
* @return returns true if success.
* @throws FeatureManagerDAOException
*/
boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException; boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException;
} }

View File

@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; 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.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyDeviceWrapper;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -35,20 +36,26 @@ public interface MonitoringDAO {
* @param devicePolicyMap <Device Id, Policy Id> * @param devicePolicyMap <Device Id, Policy Id>
* @throws MonitoringDAOException * @throws MonitoringDAOException
*/ */
@Deprecated
void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException; void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException;
void setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException; void addComplianceDetails(List<PolicyDeviceWrapper> policyDeviceWrappers) throws MonitoringDAOException;
void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException; void setDeviceAsNoneCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException;
void setDeviceAsCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException;
void addNoneComplianceFeatures(int policyComplianceStatusId, int deviceId, List<ComplianceFeature> void addNoneComplianceFeatures(int policyComplianceStatusId, int deviceId, List<ComplianceFeature>
complianceFeatures) complianceFeatures)
throws MonitoringDAOException; throws MonitoringDAOException;
ComplianceData getCompliance(int deviceId) throws MonitoringDAOException; ComplianceData getCompliance(int deviceId, int enrolmentId) throws MonitoringDAOException;
List<ComplianceData> getCompliance(List<Integer> deviceIds) throws MonitoringDAOException; List<ComplianceData> getCompliance(List<Integer> deviceIds) throws MonitoringDAOException;
List<ComplianceData> getCompliance() throws MonitoringDAOException;
List<ComplianceFeature> getNoneComplianceFeatures(int policyComplianceStatusId) throws MonitoringDAOException; List<ComplianceFeature> getNoneComplianceFeatures(int policyComplianceStatusId) throws MonitoringDAOException;
void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException; void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException;

View File

@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.dao;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.policy.mgt.core.dao.impl.FeatureDAOImpl; import org.wso2.carbon.policy.mgt.core.dao.impl.FeatureDAOImpl;
@ -38,7 +39,7 @@ public class PolicyManagementDAOFactory {
private static DataSource dataSource; private static DataSource dataSource;
private static final Log log = LogFactory.getLog(PolicyManagementDAOFactory.class); private static final Log log = LogFactory.getLog(PolicyManagementDAOFactory.class);
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>(); private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public static void init(DataSourceConfig config) { public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config); dataSource = resolveDataSource(config);
@ -48,13 +49,6 @@ public class PolicyManagementDAOFactory {
dataSource = dtSource; dataSource = dtSource;
} }
public static DataSource getDataSource() {
if (dataSource != null) {
return dataSource;
}
throw new RuntimeException("Data source is not yet configured.");
}
public static PolicyDAO getPolicyDAO() { public static PolicyDAO getPolicyDAO() {
return new PolicyDAOImpl(); return new PolicyDAOImpl();
} }
@ -91,7 +85,7 @@ public class PolicyManagementDAOFactory {
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList = List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties(); jndiConfig.getJndiProperties();
if (jndiPropertyList != null) { if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>(); Hashtable<Object, Object> jndiProperties = new Hashtable<>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue()); jndiProperties.put(prop.getName(), prop.getValue());
} }
@ -104,8 +98,14 @@ public class PolicyManagementDAOFactory {
} }
public static void beginTransaction() throws PolicyManagerDAOException { 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 { try {
Connection conn = dataSource.getConnection(); conn = dataSource.getConnection();
conn.setAutoCommit(false); conn.setAutoCommit(false);
currentConnection.set(conn); currentConnection.set(conn);
} catch (SQLException e) { } catch (SQLException e) {
@ -113,63 +113,68 @@ public class PolicyManagementDAOFactory {
} }
} }
public static Connection getConnection() throws PolicyManagerDAOException { public static Connection getConnection() {
if (currentConnection.get() == null) { Connection conn = currentConnection.get();
try { if (conn == null) {
Connection conn = dataSource.getConnection(); throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
conn.setAutoCommit(false); "This might have ideally been caused by not properly initiating the transaction via " +
currentConnection.set(conn); "'beginTransaction'/'openConnection' methods");
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while retrieving data source connection", e);
} }
} return conn;
return currentConnection.get();
} }
public static void closeConnection() { 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 { try {
con.close(); conn.close();
} catch (SQLException e) { } catch (SQLException e) {
log.warn("Error occurred while close the connection", e); log.warn("Error occurred while close the connection", e);
} }
currentConnection.remove(); currentConnection.remove();
} }
public static void commitTransaction() throws PolicyManagerDAOException { public static void commitTransaction() {
try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
if (conn != null) { 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.commit(); conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) { } 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() { public static void rollbackTransaction() {
try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
if (conn != null) { 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.rollback(); conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) { } catch (SQLException e) {
log.warn("Error occurred while roll-backing the transaction", e); log.warn("Error occurred while roll-backing the transaction", e);
} }
} }
public static void openConnection() throws SQLException { 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);
} }
} }

View File

@ -24,20 +24,67 @@ import org.wso2.carbon.policy.mgt.common.Profile;
import java.util.List; import java.util.List;
/**
* This interface represents the key operations related to policy profile.
*/
public interface ProfileDAO { public interface ProfileDAO {
/**
* This method is used to add a profile.
*
* @param profile profile object.
* @return returns added profile object.
* @throws ProfileManagerDAOException
*/
Profile addProfile(Profile profile) throws ProfileManagerDAOException; Profile addProfile(Profile profile) throws ProfileManagerDAOException;
/**
* This method is used to update a profile
* @param profile profile object.
* @return returns updated profile object.
* @throws ProfileManagerDAOException
*/
Profile updateProfile(Profile profile) throws ProfileManagerDAOException; Profile updateProfile(Profile profile) throws ProfileManagerDAOException;
/**
* This method is used to remove a profile.
* @param profile profile object
* @return returns true if success.
* @throws ProfileManagerDAOException
*/
boolean deleteProfile(Profile profile) throws ProfileManagerDAOException; boolean deleteProfile(Profile profile) throws ProfileManagerDAOException;
/**
* This method is used to remove a profile of given policy id.
* @param policyId policy id.
* @return returns true if success.
* @throws ProfileManagerDAOException
*/
boolean deleteProfile(int policyId) throws ProfileManagerDAOException; boolean deleteProfile(int policyId) throws ProfileManagerDAOException;
Profile getProfiles(int profileId) throws ProfileManagerDAOException; /**
* This method is used to retrieve a profile when id is given.
* @param profileId profile id.
* @return returns profile object.
* @throws ProfileManagerDAOException
*/
Profile getProfile(int profileId) throws ProfileManagerDAOException;
/**
* This method is used to retrieve all the profiles.
*
* @return returns a list of profile objects.
* @throws ProfileManagerDAOException
*/
List<Profile> getAllProfiles() throws ProfileManagerDAOException; List<Profile> getAllProfiles() throws ProfileManagerDAOException;
/**
* This method is used to retrieve all the profile of given device type.
*
* @param deviceType device type object.
* @return retruns list of profiles.
* @throws ProfileManagerDAOException
*/
List<Profile> getProfilesOfDeviceType(DeviceType deviceType) throws ProfileManagerDAOException; List<Profile> getProfilesOfDeviceType(DeviceType deviceType) throws ProfileManagerDAOException;
} }

View File

@ -43,115 +43,6 @@ public class FeatureDAOImpl implements FeatureDAO {
private static final Log log = LogFactory.getLog(FeatureDAOImpl.class); private static final Log log = LogFactory.getLog(FeatureDAOImpl.class);
/* @Override
public Feature addFeature(Feature feature) throws FeatureManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
try {
conn = this.getConnection();
String query = "INSERT INTO DM_FEATURES (NAME, CODE, DESCRIPTION) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, feature.getName());
stmt.setString(2, feature.getCode());
stmt.setString(3, feature.getDescription());
int affectedRows = stmt.executeUpdate();
if (log.isDebugEnabled()) {
log.debug(affectedRows + " feature is added.");
}
generatedKeys = stmt.getGeneratedKeys();
while (generatedKeys.next()) {
feature.setId(generatedKeys.getInt(1));
}
} catch (SQLException e) {
String msg = "Error occurred while adding feature to the database.";
log.error(msg, e);
throw new FeatureManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
return feature;
}*/
/* @Override
public List<Feature> addFeatures(List<Feature> features) throws FeatureManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
List<Feature> featureList = new ArrayList<Feature>();
try {
conn = this.getConnection();
String query = "INSERT INTO DM_FEATURES (NAME, CODE, DESCRIPTION) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
for (Feature feature : features) {
stmt.setString(1, feature.getName());
stmt.setString(2, feature.getCode());
stmt.setString(3, feature.getDescription());
stmt.addBatch();
}
int[] affectedRows = stmt.executeBatch();
generatedKeys = stmt.getGeneratedKeys();
if (log.isDebugEnabled()) {
log.debug(affectedRows.length + " features are added to the database.");
}
generatedKeys = stmt.getGeneratedKeys();
int i = 0;
while (generatedKeys.next()) {
features.get(i).setId(generatedKeys.getInt(1));
i++;
}
} catch (SQLException e) {
String msg = "Error occurred while adding feature to the database.";
log.error(msg, e);
throw new FeatureManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
return featureList;
}*/
/* @Override
public Feature updateFeature(Feature feature) throws FeatureManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String query = "UPDATE DM_FEATURES SET NAME = ?, CODE = ?, DESCRIPTION = ? WHERE ID = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, feature.getName());
stmt.setString(2, feature.getCode());
stmt.setString(3, feature.getDescription());
stmt.setInt(4, feature.getId());
stmt.executeUpdate();
} catch (SQLException e) {
String msg = "Error occurred while updating feature " + feature.getName() + " (Feature Name) to the
database.";
log.error(msg, e);
throw new FeatureManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
return feature;
}*/
@Override @Override
public ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException { public ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException {
return null; return null;
@ -247,7 +138,6 @@ public class FeatureDAOImpl implements FeatureDAO {
@Override @Override
public boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagerDAOException { public boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
@ -258,9 +148,10 @@ public class FeatureDAOImpl implements FeatureDAO {
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, profile.getProfileId()); stmt.setInt(1, profile.getProfileId());
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.executeUpdate(); if (stmt.executeUpdate() > 0) {
return true; return true;
}
return false;
} catch (SQLException e) { } catch (SQLException e) {
throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e); throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e);
} finally { } finally {
@ -270,7 +161,6 @@ public class FeatureDAOImpl implements FeatureDAO {
@Override @Override
public boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException { public boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
@ -280,9 +170,10 @@ public class FeatureDAOImpl implements FeatureDAO {
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, profileId); stmt.setInt(1, profileId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.executeUpdate(); if (stmt.executeUpdate() > 0) {
return true; return true;
}
return false;
} catch (SQLException e) { } catch (SQLException e) {
throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e); throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e);
} finally { } finally {
@ -448,7 +339,6 @@ public class FeatureDAOImpl implements FeatureDAO {
@Override @Override
public boolean deleteFeature(int featureId) throws FeatureManagerDAOException { public boolean deleteFeature(int featureId) throws FeatureManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
@ -459,9 +349,10 @@ public class FeatureDAOImpl implements FeatureDAO {
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, featureId); stmt.setInt(1, featureId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.executeUpdate(); if(stmt.executeUpdate() > 0) {
return true; return true;
}
return false;
} catch (SQLException e) { } catch (SQLException e) {
throw new FeatureManagerDAOException("Unable to delete the feature " + featureId + " (Feature ID) " + throw new FeatureManagerDAOException("Unable to delete the feature " + featureId + " (Feature ID) " +
"from database.", e); "from database.", e);
@ -471,13 +362,7 @@ public class FeatureDAOImpl implements FeatureDAO {
} }
private Connection getConnection() throws FeatureManagerDAOException { private Connection getConnection() throws FeatureManagerDAOException {
try {
return PolicyManagementDAOFactory.getConnection(); return PolicyManagementDAOFactory.getConnection();
} catch (PolicyManagerDAOException e) {
throw new FeatureManagerDAOException("Error occurred while obtaining a connection from the policy " +
"management metadata repository config.datasource", e);
}
} }
} }

View File

@ -24,6 +24,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; 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.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyDeviceWrapper;
import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO; 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.MonitoringDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
@ -109,7 +110,43 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override @Override
public void setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException { public void addComplianceDetails(List<PolicyDeviceWrapper> policyDeviceWrapper) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (log.isDebugEnabled()) {
for (PolicyDeviceWrapper wrapper : policyDeviceWrapper){
log.debug("Policy Id : " + wrapper.getPolicyId() + " - " + " Device Id : " + wrapper.getDeviceId());
}
}
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " +
"LAST_REQUESTED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?) ";
stmt = conn.prepareStatement(query);
for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) {
stmt.setInt(1, wrapper.getDeviceId());
stmt.setInt(2, wrapper.getPolicyId());
stmt.setInt(3, 1);
stmt.setInt(4, 1);
stmt.setTimestamp(5, currentTimestamp);
stmt.setInt(6, tenantId);
stmt.setInt(7, wrapper.getEnrolmentId());
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new MonitoringDAOException("Error occurred while adding the none compliance to the database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
}
@Override
public void setDeviceAsNoneCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet generatedKeys = null; ResultSet generatedKeys = null;
@ -118,12 +155,13 @@ public class MonitoringDAOImpl implements MonitoringDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = 0, LAST_FAILED_TIME = ?, POLICY_ID = ?," + String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = 0, LAST_FAILED_TIME = ?, POLICY_ID = ?," +
" ATTEMPTS=0 WHERE DEVICE_ID = ? AND TENANT_ID = ?"; " ATTEMPTS=0 WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setTimestamp(1, currentTimestamp); stmt.setTimestamp(1, currentTimestamp);
stmt.setInt(2, policyId); stmt.setInt(2, policyId);
stmt.setInt(3, deviceId); stmt.setInt(3, deviceId);
stmt.setInt(4, tenantId); stmt.setInt(4, tenantId);
stmt.setInt(5, enrolmentId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
@ -135,7 +173,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override @Override
public void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException { public void setDeviceAsCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet generatedKeys = null; ResultSet generatedKeys = null;
@ -144,12 +182,13 @@ public class MonitoringDAOImpl implements MonitoringDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ?, ATTEMPTS=0, LAST_SUCCESS_TIME = ?" + String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ?, ATTEMPTS=0, LAST_SUCCESS_TIME = ?" +
" WHERE DEVICE_ID = ? AND TENANT_ID = ?"; " WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, 1); stmt.setInt(1, 1);
stmt.setTimestamp(2, currentTimestamp); stmt.setTimestamp(2, currentTimestamp);
stmt.setInt(3, deviceId); stmt.setInt(3, deviceId);
stmt.setInt(4, tenantId); stmt.setInt(4, tenantId);
stmt.setInt(5, enrolmentId);
stmt.executeUpdate(); stmt.executeUpdate();
// generatedKeys = stmt.getGeneratedKeys(); // generatedKeys = stmt.getGeneratedKeys();
@ -198,7 +237,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override @Override
public ComplianceData getCompliance(int deviceId) throws MonitoringDAOException { public ComplianceData getCompliance(int deviceId, int enrolmentId) throws MonitoringDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -208,10 +247,11 @@ public class MonitoringDAOImpl implements MonitoringDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ? AND TENANT_ID = ?"; String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.setInt(3, enrolmentId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
@ -253,6 +293,43 @@ public class MonitoringDAOImpl implements MonitoringDAO {
ComplianceData complianceData = new ComplianceData(); ComplianceData complianceData = new ComplianceData();
complianceData.setId(resultSet.getInt("ID")); complianceData.setId(resultSet.getInt("ID"));
complianceData.setDeviceId(resultSet.getInt("DEVICE_ID")); complianceData.setDeviceId(resultSet.getInt("DEVICE_ID"));
complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID"));
complianceData.setPolicyId(resultSet.getInt("POLICY_ID"));
complianceData.setStatus(resultSet.getBoolean("STATUS"));
complianceData.setAttempts(resultSet.getInt("ATTEMPTS"));
complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME"));
complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME"));
complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME"));
complianceDataList.add(complianceData);
}
return complianceDataList;
} catch (SQLException e) {
throw new MonitoringDAOException("Unable to retrieve compliance data from database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
public List<ComplianceData> getCompliance() throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<ComplianceData> complianceDataList = new ArrayList<>();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
ComplianceData complianceData = new ComplianceData();
complianceData.setId(resultSet.getInt("ID"));
complianceData.setDeviceId(resultSet.getInt("DEVICE_ID"));
complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID"));
complianceData.setPolicyId(resultSet.getInt("POLICY_ID")); complianceData.setPolicyId(resultSet.getInt("POLICY_ID"));
complianceData.setStatus(resultSet.getBoolean("STATUS")); complianceData.setStatus(resultSet.getBoolean("STATUS"));
complianceData.setAttempts(resultSet.getInt("ATTEMPTS")); complianceData.setAttempts(resultSet.getInt("ATTEMPTS"));
@ -382,12 +459,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
private Connection getConnection() throws MonitoringDAOException { private Connection getConnection() throws MonitoringDAOException {
try {
return PolicyManagementDAOFactory.getConnection(); return PolicyManagementDAOFactory.getConnection();
} catch (PolicyManagerDAOException e) {
throw new MonitoringDAOException("Error occurred while obtaining a connection from the policy " +
"management metadata repository config.datasource", e);
}
} }
} }

View File

@ -420,11 +420,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setString(1, name); stmt.setString(1, name);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
exist = resultSet.next();
if (resultSet.next()) {
//TODO: FIXME
exist = resultSet.getBoolean(1);
}
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while checking whether criterion (" + name + throw new PolicyManagerDAOException("Error occurred while checking whether criterion (" + name +
") exists", e); ") exists", e);
@ -1308,7 +1304,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(3, enrollmentId); stmt.setInt(3, enrollmentId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
while (resultSet.next()) { if (resultSet.next()) {
return resultSet.getInt("POLICY_ID"); return resultSet.getInt("POLICY_ID");
} }
} catch (SQLException e) { } catch (SQLException e) {

View File

@ -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.ProfileDAO;
import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException; 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.dao.util.PolicyManagementDAOUtil;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -133,7 +132,6 @@ public class ProfileDAOImpl implements ProfileDAO {
@Override @Override
public boolean deleteProfile(Profile profile) throws ProfileManagerDAOException { public boolean deleteProfile(Profile profile) throws ProfileManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -142,9 +140,10 @@ public class ProfileDAOImpl implements ProfileDAO {
String query = "DELETE FROM DM_PROFILE WHERE ID = ?"; String query = "DELETE FROM DM_PROFILE WHERE ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, profile.getProfileId()); stmt.setInt(1, profile.getProfileId());
stmt.executeUpdate(); if (stmt.executeUpdate() > 0) {
return true; return true;
}
return false;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while deleting the profile from the data base."; String msg = "Error occurred while deleting the profile from the data base.";
log.error(msg); log.error(msg);
@ -164,9 +163,10 @@ public class ProfileDAOImpl implements ProfileDAO {
String query = "DELETE FROM DM_PROFILE WHERE ID = ?"; String query = "DELETE FROM DM_PROFILE WHERE ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, profileId); stmt.setInt(1, profileId);
stmt.executeUpdate(); if (stmt.executeUpdate() > 0) {
return true; return true;
}
return false;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while deleting the profile from the data base."; String msg = "Error occurred while deleting the profile from the data base.";
log.error(msg); log.error(msg);
@ -178,8 +178,7 @@ public class ProfileDAOImpl implements ProfileDAO {
@Override @Override
public Profile getProfiles(int profileId) throws ProfileManagerDAOException { public Profile getProfile(int profileId) throws ProfileManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -217,11 +216,10 @@ public class ProfileDAOImpl implements ProfileDAO {
@Override @Override
public List<Profile> getAllProfiles() throws ProfileManagerDAOException { public List<Profile> getAllProfiles() throws ProfileManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<Profile> profileList = new ArrayList<Profile>(); List<Profile> profileList = new ArrayList<>();
try { try {
//TODO : Fix with TenantID. //TODO : Fix with TenantID.
@ -259,12 +257,10 @@ public class ProfileDAOImpl implements ProfileDAO {
@Override @Override
public List<Profile> getProfilesOfDeviceType(DeviceType deviceType) throws ProfileManagerDAOException { public List<Profile> getProfilesOfDeviceType(DeviceType deviceType) throws ProfileManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<Profile> profileList = new ArrayList<Profile>(); List<Profile> profileList = new ArrayList<>();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "SELECT * FROM DM_PROFILE WHERE DEVICE_TYPE_ID = ?"; String query = "SELECT * FROM DM_PROFILE WHERE DEVICE_TYPE_ID = ?";
@ -283,7 +279,6 @@ public class ProfileDAOImpl implements ProfileDAO {
profileList.add(profile); profileList.add(profile);
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while reading the profile list from the database."; String msg = "Error occurred while reading the profile list from the database.";
log.error(msg, e); log.error(msg, e);
@ -296,12 +291,7 @@ public class ProfileDAOImpl implements ProfileDAO {
private Connection getConnection() throws ProfileManagerDAOException { private Connection getConnection() throws ProfileManagerDAOException {
try {
return PolicyManagementDAOFactory.getConnection(); return PolicyManagementDAOFactory.getConnection();
} catch (PolicyManagerDAOException e) {
throw new ProfileManagerDAOException("Error occurred while obtaining a connection from the policy " +
"management metadata repository config.datasource", e);
}
} }
} }

View File

@ -16,7 +16,6 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.policy.mgt.core.enforcement; package org.wso2.carbon.policy.mgt.core.enforcement;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;

View File

@ -39,10 +39,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceIm
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.ProfileFeature; 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.*;
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.spi.PolicyMonitoringService; import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.dao.*;
import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl;
@ -98,7 +95,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
// run. // run.
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
ComplianceData cmd = monitoringDAO.getCompliance(device.getId()); ComplianceData cmd = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId());
complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier,
policy, deviceResponse); policy, deviceResponse);
@ -118,7 +115,8 @@ public class MonitoringManagerImpl implements MonitoringManager {
if (complianceFeatures != null && !complianceFeatures.isEmpty()) { if (complianceFeatures != null && !complianceFeatures.isEmpty()) {
try { try {
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); monitoringDAO.setDeviceAsNoneCompliance(device.getId(), device.getEnrolmentInfo().getId(),
policy.getId());
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Compliance status primary key " + complianceData.getId()); log.debug("Compliance status primary key " + complianceData.getId());
} }
@ -141,7 +139,8 @@ public class MonitoringManagerImpl implements MonitoringManager {
} else { } else {
try { try {
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); monitoringDAO.setDeviceAsCompliance(device.getId(), device.getEnrolmentInfo().getId(), policy
.getId());
monitoringDAO.deleteNoneComplianceData(complianceData.getId()); monitoringDAO.deleteNoneComplianceData(complianceData.getId());
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} finally { } finally {
@ -175,7 +174,8 @@ public class MonitoringManagerImpl implements MonitoringManager {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier); Device device = service.getDevice(deviceIdentifier);
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
ComplianceData complianceData = monitoringDAO.getCompliance(device.getId()); ComplianceData complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo()
.getId());
if (complianceData == null || !complianceData.isStatus()) { if (complianceData == null || !complianceData.isStatus()) {
return false; return false;
} }
@ -203,7 +203,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier); Device device = service.getDevice(deviceIdentifier);
complianceData = monitoringDAO.getCompliance(device.getId()); complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId());
List<ComplianceFeature> complianceFeatures = List<ComplianceFeature> complianceFeatures =
monitoringDAO.getNoneComplianceFeatures(complianceData.getId()); monitoringDAO.getNoneComplianceFeatures(complianceData.getId());
complianceData.setComplianceFeatures(complianceFeatures); complianceData.setComplianceFeatures(complianceFeatures);
@ -226,21 +226,27 @@ public class MonitoringManagerImpl implements MonitoringManager {
@Override @Override
public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException { public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException {
ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
//int tenantId = PolicyManagerUtil.getTenantId(); //int tenantId = PolicyManagerUtil.getTenantId();
Map<Integer, Device> deviceIds = new HashMap<>(); Map<Integer, Device> deviceIds = new HashMap<>();
List<ComplianceData> complianceDatas; List<ComplianceData> complianceDatas = new ArrayList<>();
HashMap<Integer, Integer> devicePolicyIdMap; HashMap<Integer, Integer> devicePolicyIdMap;
try {
PolicyManagementDAOFactory.openConnection();
List<ComplianceData> cd = monitoringDAO.getCompliance();
for (Device device : devices) { for (Device device : devices) {
deviceIds.put(device.getId(), device); deviceIds.put(device.getId(), device);
}
for (ComplianceData data : cd) {
if (device.getId() == data.getDeviceId() && device.getEnrolmentInfo().getId() == data
.getEnrolmentId()) {
complianceDatas.add(data);
}
}
}
List<Integer> deviceIDs = new ArrayList<>(deviceIds.keySet()); List<Integer> deviceIDs = new ArrayList<>(deviceIds.keySet());
try {
PolicyManagementDAOFactory.openConnection();
complianceDatas = monitoringDAO.getCompliance(deviceIDs);
devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs); devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs);
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e);
@ -256,7 +262,9 @@ public class MonitoringManagerImpl implements MonitoringManager {
Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>(); Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();
Map<Integer, Device> inactiveDeviceIds = new HashMap<>(); Map<Integer, Device> inactiveDeviceIds = new HashMap<>();
Map<Integer, Device> deviceToMarkUnreachable = new HashMap<>(); Map<Integer, Device> deviceToMarkUnreachable = new HashMap<>();
Map<Integer, Integer> firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); //Map<Integer, Integer> firstTimeDeviceIdsWithPolicyIds = new HashMap<>();
List<PolicyDeviceWrapper> firstTimeDevices = new ArrayList<>();
Map<Integer, ComplianceData> tempMap = new HashMap<>(); Map<Integer, ComplianceData> tempMap = new HashMap<>();
@ -287,21 +295,31 @@ public class MonitoringManagerImpl implements MonitoringManager {
for (Device device : devices) { for (Device device : devices) {
if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) { if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) {
deviceIdsToAddOperation.put(device.getId(), device); deviceIdsToAddOperation.put(device.getId(), device);
firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId()));
PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper();
policyDeviceWrapper.setDeviceId(device.getId());
policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId());
policyDeviceWrapper.setPolicyId(devicePolicyIdMap.get(device.getId()));
firstTimeDevices.add(policyDeviceWrapper);
// firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId()));
} }
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("These devices are in the system for the first time"); log.debug("These devices are in the system for the first time");
for (Map.Entry<Integer, Integer> map : firstTimeDeviceIdsWithPolicyIds.entrySet()) { for (PolicyDeviceWrapper wrapper : firstTimeDevices) {
log.debug("First time device primary key : " + map.getKey() + " & policy id " + map.getValue()); log.debug("First time device primary key : " + wrapper.getDeviceId() + " & policy id " +
wrapper.getPolicyId());
} }
} }
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
if (!deviceIdsToAddOperation.isEmpty()) { if (!deviceIdsToAddOperation.isEmpty()) {
monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); // monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds);
monitoringDAO.addComplianceDetails(firstTimeDevices);
} }
if (!deviceIdsWithExistingOperation.isEmpty()) { if (!deviceIdsWithExistingOperation.isEmpty()) {
@ -327,10 +345,11 @@ public class MonitoringManagerImpl implements MonitoringManager {
} }
} }
// TODO : This should be uncommented, this is to mark the device as unreachable, But given the current implementation // TODO : This should be uncommented, this is to mark the device as unreachable, But given the current
// we are not able to do so. // implementation we are not able to do so.
// if(!deviceToMarkUnreachable.isEmpty()) { // if(!deviceToMarkUnreachable.isEmpty()) {
// ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
// decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices( // decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices(
// new ArrayList<>(deviceToMarkUnreachable.values()))); // new ArrayList<>(deviceToMarkUnreachable.values())));
// } // }
@ -363,7 +382,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
service.addOperation(monitoringOperation, deviceIdentifiers); service.addOperation(monitoringOperation, deviceIdentifiers);
} }
private List<DeviceIdentifier> getDeviceIdentifiersFromDevices(List<Device> devices) { private List<DeviceIdentifier> getDeviceIdentifiersFromDevices(List<Device> devices) {

View File

@ -20,10 +20,12 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.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.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; 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.DeviceManagementProviderService;
@ -46,13 +48,14 @@ public class PolicyManagerImpl implements PolicyManager {
private ProfileDAO profileDAO; private ProfileDAO profileDAO;
private FeatureDAO featureDAO; private FeatureDAO featureDAO;
private ProfileManager profileManager; private ProfileManager profileManager;
private PolicyCacheManager policyCacheManager; private DeviceDAO deviceDAO;
private static Log log = LogFactory.getLog(PolicyManagerImpl.class); private static Log log = LogFactory.getLog(PolicyManagerImpl.class);
public PolicyManagerImpl() { public PolicyManagerImpl() {
this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO();
this.profileDAO = PolicyManagementDAOFactory.getProfileDAO(); this.profileDAO = PolicyManagementDAOFactory.getProfileDAO();
this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.profileManager = new ProfileManagerImpl(); this.profileManager = new ProfileManagerImpl();
} }
@ -105,6 +108,9 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias());
} }
if(policy.isActive()){
policyDAO.activatePolicy(policy.getId());
}
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
@ -316,14 +322,18 @@ public class PolicyManagerImpl implements PolicyManager {
@Override @Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList,
Policy policy) throws PolicyManagementException { Policy policy) throws PolicyManagementException {
try {
List<Device> deviceList = new ArrayList<>(); List<Device> deviceList = new ArrayList<>();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) { for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) {
deviceList.add(service.getDevice(deviceIdentifier)); 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(); PolicyManagementDAOFactory.beginTransaction();
if (policy.getId() == 0) { if (policy.getId() == 0) {
policyDAO.addPolicy(policy); policyDAO.addPolicy(policy);
@ -347,9 +357,6 @@ public class PolicyManagerImpl implements PolicyManager {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while adding the policy (" throw new PolicyManagementException("Error occurred while adding the policy ("
+ policy.getId() + " - " + policy.getPolicyName() + ")", e); + policy.getId() + " - " + policy.getPolicyName() + ")", e);
} catch (DeviceManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while adding the policy to device list", e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -432,7 +439,7 @@ public class PolicyManagerImpl implements PolicyManager {
policy = policyDAO.getPolicyByProfileID(profileId); policy = policyDAO.getPolicyByProfileID(profileId);
roleNames = policyDAO.getPolicyAppliedRoles(policy.getId()); roleNames = policyDAO.getPolicyAppliedRoles(policy.getId());
profile = profileDAO.getProfiles(profileId); profile = profileDAO.getProfile(profileId);
policy.setProfile(profile); policy.setProfile(profile);
policy.setRoles(roleNames); policy.setRoles(roleNames);
@ -467,7 +474,7 @@ public class PolicyManagerImpl implements PolicyManager {
policy = policyDAO.getPolicy(policyId); policy = policyDAO.getPolicy(policyId);
roleNames = policyDAO.getPolicyAppliedRoles(policyId); roleNames = policyDAO.getPolicyAppliedRoles(policyId);
Profile profile = profileDAO.getProfiles(policy.getProfileId()); Profile profile = profileDAO.getProfile(policy.getProfileId());
policy.setProfile(profile); policy.setProfile(profile);
policy.setRoles(roleNames); policy.setRoles(roleNames);
@ -668,11 +675,13 @@ public class PolicyManagerImpl implements PolicyManager {
List<Device> deviceList = new ArrayList<>(); List<Device> deviceList = new ArrayList<>();
List<Integer> deviceIds; List<Integer> deviceIds;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
List<Device> allDevices = service.getAllDevices(); List<Device> allDevices = service.getAllDevices();
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
//int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); //int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId);
@ -707,6 +716,7 @@ public class PolicyManagerImpl implements PolicyManager {
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
return deviceList; return deviceList;
} }
@ -861,12 +871,9 @@ public class PolicyManagerImpl implements PolicyManager {
@Override @Override
public int getPolicyCount() throws PolicyManagementException { public int getPolicyCount() throws PolicyManagementException {
int policyCount;
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
policyCount = policyDAO.getPolicyCount(); return policyDAO.getPolicyCount();
return policyCount;
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting policy count", e); throw new PolicyManagementException("Error occurred while getting policy count", e);
} catch (SQLException e) { } catch (SQLException e) {

View File

@ -143,15 +143,13 @@ public class ProfileManagerImpl implements ProfileManager {
public Profile getProfile(int profileId) throws ProfileManagementException { public Profile getProfile(int profileId) throws ProfileManagementException {
Profile profile; Profile profile;
List<ProfileFeature> featureList; List<ProfileFeature> featureList;
DeviceType deviceType; DeviceType deviceType = null;
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
profile = profileDAO.getProfiles(profileId); profile = profileDAO.getProfile(profileId);
featureList = featureDAO.getFeaturesForProfile(profileId); featureList = featureDAO.getFeaturesForProfile(profileId);
profile.setProfileFeaturesList(featureList); profile.setProfileFeaturesList(featureList);
} catch (ProfileManagerDAOException e) { } catch (ProfileManagerDAOException e) {
throw new ProfileManagementException("Error occurred while getting profile id (" + profileId + ")", e); throw new ProfileManagementException("Error occurred while getting profile id (" + profileId + ")", e);
} catch (FeatureManagerDAOException e) { } catch (FeatureManagerDAOException e) {
@ -161,7 +159,6 @@ public class ProfileManagerImpl implements ProfileManager {
throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
try { try {
@ -185,14 +182,19 @@ public class ProfileManagerImpl implements ProfileManager {
public List<Profile> getAllProfiles() throws ProfileManagementException { public List<Profile> getAllProfiles() throws ProfileManagementException {
List<Profile> profileList; List<Profile> profileList;
List<DeviceType> deviceTypes; List<DeviceType> deviceTypes;
try {
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
deviceTypes = deviceTypeDAO.getDeviceTypes(); 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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
profileList = profileDAO.getAllProfiles(); profileList = profileDAO.getAllProfiles();
List<ProfileFeature> featureList = featureDAO.getAllProfileFeatures(); List<ProfileFeature> featureList = featureDAO.getAllProfileFeatures();
@ -217,8 +219,6 @@ public class ProfileManagerImpl implements ProfileManager {
throw new ProfileManagementException("Error occurred while getting profiles", e); throw new ProfileManagementException("Error occurred while getting profiles", e);
} catch (FeatureManagerDAOException e) { } catch (FeatureManagerDAOException e) {
throw new ProfileManagementException("Error occurred while getting features related to profiles", 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) { } catch (SQLException e) {
throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
@ -233,13 +233,19 @@ public class ProfileManagerImpl implements ProfileManager {
List<Profile> profileList; List<Profile> profileList;
List<ProfileFeature> featureList; List<ProfileFeature> featureList;
DeviceType deviceType; DeviceType deviceType;
try {
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
deviceType = deviceTypeDAO.getDeviceType(deviceTypeName); 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 { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
profileList = profileDAO.getProfilesOfDeviceType(deviceType); profileList = profileDAO.getProfilesOfDeviceType(deviceType);
@ -253,12 +259,9 @@ public class ProfileManagerImpl implements ProfileManager {
} }
} }
profile.setProfileFeaturesList(profileFeatureList); profile.setProfileFeaturesList(profileFeatureList);
} }
} catch (ProfileManagerDAOException e) { } catch (ProfileManagerDAOException e) {
throw new ProfileManagementException("Error occurred while getting profiles", 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) { } catch (FeatureManagerDAOException e) {
throw new ProfileManagementException("Error occurred while getting profile features types", e); throw new ProfileManagementException("Error occurred while getting profile features types", e);
} catch (SQLException e) { } catch (SQLException e) {

View File

@ -77,7 +77,6 @@ public class MonitoringTask implements Task {
try { try {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementProviderService deviceManagementProviderService =
PolicyManagementDataHolder.getInstance().getDeviceManagementService(); PolicyManagementDataHolder.getInstance().getDeviceManagementService();
@ -100,15 +99,21 @@ public class MonitoringTask implements Task {
deviceType.getName()); deviceType.getName());
} }
for (Device device : devices) { for (Device device : devices) {
if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.INACTIVE) || EnrolmentInfo.Status status = device.getEnrolmentInfo().getStatus();
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.BLOCKED)) { if (status.equals(EnrolmentInfo.Status.INACTIVE) ||
status.equals(EnrolmentInfo.Status.BLOCKED) ||
status.equals(EnrolmentInfo.Status.REMOVED) ||
status.equals(EnrolmentInfo.Status.UNCLAIMED) ||
status.equals(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED) ||
status.equals(EnrolmentInfo.Status.SUSPENDED)) {
continue; continue;
} else { } else {
notifiableDevices.add(device); notifiableDevices.add(device);
} }
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Following devices selected to send the notification for " + deviceType.getName()); log.debug("Following devices selected to send the notification for " +
deviceType.getName());
for (Device device : notifiableDevices) { for (Device device : notifiableDevices) {
log.debug(device.getDeviceIdentifier()); log.debug(device.getDeviceIdentifier());
} }

View File

@ -39,6 +39,7 @@ public final class PolicyManagementConstants {
public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER"; public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER";
public static final String DM_CACHE = "DM_CACHE"; public static final String DM_CACHE = "DM_CACHE";
public static final String DM_CACHE_LIST = "DM_CACHE_LIST";
public static final String DELEGATION_TASK_TYPE = "DELEGATION__TASK"; public static final String DELEGATION_TASK_TYPE = "DELEGATION__TASK";

View File

@ -152,10 +152,28 @@ public class PolicyManagerUtil {
} }
public static Cache getCacheManagerImpl() { // public static Cache getCacheManagerImpl() {
return Caching.getCacheManagerFactory() // return Caching.getCacheManagerFactory()
.getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants // .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants
.DM_CACHE); // .DM_CACHE);
// }
public static Cache<Integer, Policy> getPolicyCache(String name){
CacheManager manager = getCacheManager();
return (manager != null) ? manager.<Integer, Policy>getCache(name) :
Caching.getCacheManager().<Integer, Policy>getCache(name);
}
public static Cache<Integer, List<Policy>> getPolicyListCache(String name){
CacheManager manager = getCacheManager();
return (manager != null) ? manager.<Integer, List<Policy>>getCache(name) :
Caching.getCacheManager().<Integer, List<Policy>>getCache(name);
}
private static CacheManager getCacheManager() {
return Caching.getCacheManagerFactory().getCacheManager(
PolicyManagementConstants.DM_CACHE_MANAGER);
} }

View File

@ -53,11 +53,12 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
private static final String ANDROID = "android"; private static final String ANDROID = "android";
DeviceIdentifier identifier = new DeviceIdentifier(); private DeviceIdentifier identifier = new DeviceIdentifier();
@BeforeClass @BeforeClass
@Override @Override
public void init() throws Exception { public void init() throws Exception {
} }
@Test @Test

View File

@ -21,19 +21,21 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; 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.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*; 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.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.util.*; import org.wso2.carbon.policy.mgt.core.util.*;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
@ -58,16 +60,28 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test @Test
public void addDeviceType() throws DeviceManagementDAOException { public void addDeviceType() throws DeviceManagementDAOException {
try {
DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
deviceTypeDAO.addDeviceType(DeviceTypeCreator.getDeviceType()); 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")) @Test(dependsOnMethods = ("addDeviceType"))
public void addDevice() throws DeviceManagementDAOException, DeviceManagementException { public void addDevice() throws DeviceManagementException, PolicyManagementException {
DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
DeviceType type = DeviceTypeCreator.getDeviceType(); DeviceType type = DeviceTypeCreator.getDeviceType();
devices = DeviceCreator.getDeviceList(type); devices = DeviceCreator.getDeviceList(type);
devices.addAll(DeviceCreator.getDeviceList2(type)); devices.addAll(DeviceCreator.getDeviceList2(type));
@ -75,10 +89,21 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
devices.addAll(DeviceCreator.getDeviceList4(type)); devices.addAll(DeviceCreator.getDeviceList4(type));
devices.addAll(DeviceCreator.getDeviceList5(type)); devices.addAll(DeviceCreator.getDeviceList5(type));
devices.addAll(DeviceCreator.getDeviceList6(type)); devices.addAll(DeviceCreator.getDeviceList6(type));
try {
DeviceManagementDAOFactory.beginTransaction();
for (Device device : devices) { for (Device device : devices) {
int id = deviceDAO.addDevice(type.getId(), device, -1234); int id = deviceDAO.addDevice(type.getId(), device, -1234);
enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -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();
}
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
@ -376,8 +401,6 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
for (Device device : devices) { for (Device device : devices) {
log.debug("Device Name : " + device.getDeviceIdentifier()); log.debug("Device Name : " + device.getDeviceIdentifier());
} }
} }
} }

View File

@ -37,6 +37,10 @@
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
@ -45,16 +49,52 @@
<instructions> <instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName> <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Activator>org.wso2.carbon.webapp.authenticator.framework.internal.WebappAuthenticatorFrameworkBundleActivator</Bundle-Activator>
<!--<Require-Bundle>org.wso2.carbon.tomcat.patch</Require-Bundle>-->
<Private-Package> <Private-Package>
org.wso2.carbon.webapp.authenticator.framework.internal org.wso2.carbon.webapp.authenticator.framework.internal
</Private-Package> </Private-Package>
<DynamicImport-Package>*</DynamicImport-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.webapp.authenticator.framework.internal, !org.wso2.carbon.webapp.authenticator.framework.internal,
org.wso2.carbon.webapp.authenticator.framework.* org.wso2.carbon.webapp.authenticator.framework.*
</Export-Package> </Export-Package>
<Import-Package>
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,
javax.servlet.http,
javax.xml,
org.apache.axis2.transport.http,
org.wso2.carbon.apimgt.impl,
org.wso2.carbon.registry.api
</Import-Package>
<!--<Fragment-Host>tomcat</Fragment-Host>--> <!--<Fragment-Host>tomcat</Fragment-Host>-->
</instructions> </instructions>
</configuration> </configuration>
@ -104,8 +144,8 @@
<artifactId>org.wso2.carbon.core.services</artifactId> <artifactId>org.wso2.carbon.core.services</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId> <artifactId>nimbus-jose-jwt</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -1,24 +0,0 @@
/*
* 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;
public class APIInfo {
}

View File

@ -1,33 +0,0 @@
/*
* 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;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
public class APIMapperContextListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_INIT_EVENT.equals(lifecycleEvent.getType())) {
}
}
}

View File

@ -18,19 +18,34 @@
*/ */
package org.wso2.carbon.webapp.authenticator.framework; package org.wso2.carbon.webapp.authenticator.framework;
import org.wso2.carbon.user.core.service.RealmService;
public class DataHolder { public class DataHolder {
private static WebappAuthenticatorRepository repository; private WebappAuthenticatorRepository repository;
private RealmService realmService;
private DataHolder() {} private DataHolder() {}
public static void setWebappAuthenticatorRepository (WebappAuthenticatorRepository repository) { private static DataHolder thisInstance = new DataHolder();
DataHolder.repository = repository;
public static DataHolder getInstance() {
return thisInstance;
} }
public static WebappAuthenticatorRepository getWebappAuthenticatorRepository() { public void setWebappAuthenticatorRepository (WebappAuthenticatorRepository repository) {
this.repository = repository;
}
public WebappAuthenticatorRepository getWebappAuthenticatorRepository() {
return repository; return repository;
} }
public RealmService getRealmService() {
return realmService;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
}
} }

View File

@ -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.webapp.authenticator.framework;
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.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.CompositeValve;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import javax.servlet.http.HttpServletResponse;
import java.util.StringTokenizer;
public class WebappAuthenticationHandler extends CarbonTomcatValve {
private static final Log log = LogFactory.getLog(WebappAuthenticationHandler.class);
@Override
public void invoke(Request request, Response response, CompositeValve compositeValve) {
if (this.isContextSkipped(request) || (this.isNonAdminService(request) && this.skipAuthentication(request))) {
this.getNext().invoke(request, response, compositeValve);
return;
}
WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request);
if (authenticator == null) {
String msg = "Failed to load an appropriate authenticator to authenticate the request";
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
return;
}
WebappAuthenticator.Status status = authenticator.authenticate(request, response);
this.processResponse(request, response, compositeValve, status);
}
private boolean isNonAdminService(Request request) {
String param = request.getContext().findParameter("isAdminService");
return !(param != null && Boolean.parseBoolean(param));
}
private boolean skipAuthentication(Request request) {
String param = request.getContext().findParameter("doAuthentication");
return (param == null || !Boolean.parseBoolean(param));
}
private boolean isContextSkipped(Request request) {
String ctx = request.getContext().getPath();
if (ctx == null || "".equals(ctx)) {
ctx = request.getContextPath();
if (ctx == null || "".equals(ctx)) {
String requestUri = request.getRequestURI();
if ("/".equals(requestUri)) {
return true;
}
StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/");
if (!tokenizer.hasMoreTokens()) {
return false;
}
ctx = tokenizer.nextToken();
}
}
return (ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services"));
}
private void processResponse(Request request, Response response, CompositeValve compositeValve,
WebappAuthenticator.Status status) {
switch (status) {
case SUCCESS:
case CONTINUE:
this.getNext().invoke(request, response, compositeValve);
break;
case FAILURE:
String msg = "Failed to authorize incoming request";
log.error(msg);
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
break;
}
}
}

View File

@ -19,17 +19,25 @@
package org.wso2.carbon.webapp.authenticator.framework; package org.wso2.carbon.webapp.authenticator.framework;
import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Request;
import org.apache.catalina.util.Base64; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.CharChunk; import java.util.Map;
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 class WebappAuthenticatorFactory {
public static WebappAuthenticator getAuthenticator(String authScheme) { public static WebappAuthenticator getAuthenticator(String authScheme) {
return DataHolder.getWebappAuthenticatorRepository().getAuthenticator(authScheme); return DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme);
}
public static WebappAuthenticator getAuthenticator(Request request) {
Map<String, WebappAuthenticator> authenticators =
DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators();
for (WebappAuthenticator authenticator : authenticators.values()) {
if (authenticator.canHandle(request)) {
return authenticator;
}
}
return null;
} }
} }

View File

@ -24,6 +24,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.CompositeValve; import org.wso2.carbon.tomcat.ext.valves.CompositeValve;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList; import java.util.ArrayList;

View File

@ -18,15 +18,18 @@
*/ */
package org.wso2.carbon.webapp.authenticator.framework; package org.wso2.carbon.webapp.authenticator.framework;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class WebappAuthenticatorRepository { public class WebappAuthenticatorRepository {
private Map<String, WebappAuthenticator> authenticators; private Map<String, WebappAuthenticator> authenticators;
public WebappAuthenticatorRepository() { public WebappAuthenticatorRepository() {
this.authenticators = new HashMap<String, WebappAuthenticator>(); this.authenticators = new ConcurrentHashMap<>();
} }
public void addAuthenticator(WebappAuthenticator authenticator) { public void addAuthenticator(WebappAuthenticator authenticator) {
@ -37,4 +40,8 @@ public class WebappAuthenticatorRepository {
return authenticators.get(name); return authenticators.get(name);
} }
public Map<String, WebappAuthenticator> getAuthenticators() {
return authenticators;
}
} }

View File

@ -24,14 +24,23 @@ import org.apache.catalina.util.Base64;
import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.MessageBytes;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.Constants;
public class BasicAuthAuthenticator implements WebappAuthenticator { public class BasicAuthAuthenticator implements WebappAuthenticator {
private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth";
@Override @Override
public boolean isAuthenticated(Request request) { public boolean canHandle(Request request) {
MessageBytes authorization =
request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
if (authorization != null) {
authorization.toBytes();
ByteChunk authBC = authorization.getByteChunk();
if (authBC.startsWithIgnoreCase("basic ", 0)) {
return true;
}
}
return false; return false;
} }
@ -47,7 +56,8 @@ public class BasicAuthAuthenticator implements WebappAuthenticator {
private Credentials getCredentials(Request request) { private Credentials getCredentials(Request request) {
Credentials credentials = null; Credentials credentials = null;
MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization"); MessageBytes authorization =
request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
if (authorization != null) { if (authorization != null) {
authorization.toBytes(); authorization.toBytes();
ByteChunk authBC = authorization.getByteChunk(); ByteChunk authBC = authorization.getByteChunk();

View File

@ -0,0 +1,139 @@
/*
* 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 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 canHandle(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;
}
}

View File

@ -30,7 +30,6 @@ import org.wso2.carbon.apimgt.core.gateway.APITokenAuthenticator;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil;
import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.Constants;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -39,13 +38,28 @@ import java.util.regex.Pattern;
public class OAuthAuthenticator implements WebappAuthenticator { public class OAuthAuthenticator implements WebappAuthenticator {
private static final String OAUTH_AUTHENTICATOR = "OAuth"; private static final String OAUTH_AUTHENTICATOR = "OAuth";
private static APITokenAuthenticator authenticator = new APITokenAuthenticator();
private static final String REGEX_BEARER_PATTERN = "[B|b]earer\\s"; private static final String REGEX_BEARER_PATTERN = "[B|b]earer\\s";
private static final Pattern PATTERN = Pattern.compile(REGEX_BEARER_PATTERN);
private static APITokenAuthenticator authenticator = new APITokenAuthenticator();
private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); private static final Log log = LogFactory.getLog(OAuthAuthenticator.class);
@Override @Override
public boolean isAuthenticated(Request request) { public boolean canHandle(Request request) {
MessageBytes authorization =
request.getCoyoteRequest().getMimeHeaders().
getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
String tokenValue;
if (authorization != null) {
authorization.toBytes();
ByteChunk authBC = authorization.getByteChunk();
tokenValue = authBC.toString();
Matcher matcher = PATTERN.matcher(tokenValue);
if (matcher.find()) {
return true;
}
}
return false; return false;
} }
@ -74,7 +88,8 @@ public class OAuthAuthenticator implements WebappAuthenticator {
} else { } else {
String bearerToken = this.getBearerToken(request); String bearerToken = this.getBearerToken(request);
boolean isAuthenticated = boolean isAuthenticated =
AuthenticationFrameworkUtil.doAuthenticate(context, apiVersion, bearerToken, authLevel, domain); AuthenticationFrameworkUtil.doAuthenticate(context, apiVersion,
bearerToken, authLevel, domain);
return (isAuthenticated) ? Status.SUCCESS : Status.FAILURE; return (isAuthenticated) ? Status.SUCCESS : Status.FAILURE;
} }
} catch (APIManagementException e) { } catch (APIManagementException e) {
@ -92,18 +107,15 @@ public class OAuthAuthenticator implements WebappAuthenticator {
} }
private String getBearerToken(Request request) { private String getBearerToken(Request request) {
MessageBytes authorization = MessageBytes authorization =
request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); request.getCoyoteRequest().getMimeHeaders().
getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
String tokenValue = null; String tokenValue = null;
if (authorization != null) { if (authorization != null) {
authorization.toBytes(); authorization.toBytes();
ByteChunk authBC = authorization.getByteChunk(); ByteChunk authBC = authorization.getByteChunk();
tokenValue = authBC.toString(); tokenValue = authBC.toString();
Pattern pattern = Pattern.compile(REGEX_BEARER_PATTERN); Matcher matcher = PATTERN.matcher(tokenValue);
Matcher matcher = pattern.matcher(tokenValue);
if (matcher.find()) { if (matcher.find()) {
tokenValue = tokenValue.substring(matcher.end()); tokenValue = tokenValue.substring(matcher.end());
} }

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.webapp.authenticator.framework; package org.wso2.carbon.webapp.authenticator.framework.authenticator;
import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response; import org.apache.catalina.connector.Response;
@ -27,7 +27,7 @@ public interface WebappAuthenticator {
SUCCESS, FAILURE, CONTINUE SUCCESS, FAILURE, CONTINUE
} }
boolean isAuthenticated(Request request); boolean canHandle(Request request);
Status authenticate(Request request, Response response); Status authenticate(Request request, Response response);

View File

@ -1,59 +0,0 @@
/*
* 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.authorizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.registry.api.Collection;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.config.Permission;
public class PermissionAuthorizerUtil {
private static Registry registry = CarbonContext.getThreadLocalCarbonContext().
getRegistry(RegistryType.SYSTEM_GOVERNANCE);
private static final String PROPERTY_NAME = "name";
private static final String PATH_PERMISSION = "/permission";
private static final Log log = LogFactory.getLog(PermissionAuthorizerUtil.class);
public static void addPermission(Permission permission) {
if (registry == null) {
throw new IllegalArgumentException("Registry instance retrieved is null");
}
if (permission == null) {
throw new IllegalArgumentException("Permission argument is null");
}
try {
Collection collection = registry.newCollection();
collection.setProperty(PROPERTY_NAME, permission.getName());
registry.put(PATH_PERMISSION + permission.getPath(), collection);
} catch (RegistryException e) {
String errorMsg = "Error occured while adding permission '" + permission.getName() +
"' to registry. ";
log.error(errorMsg + e.getMessage());
}
}
}

View File

@ -20,43 +20,49 @@ package org.wso2.carbon.webapp.authenticator.framework.internal;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleActivator; import org.osgi.service.component.ComponentContext;
import org.osgi.framework.BundleContext;
import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer; 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.DataHolder;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationHandler;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorFrameworkValve; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepository; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepository;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.PermissionAuthorizerUtil;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.PermissionAuthorizerValve; import org.wso2.carbon.webapp.authenticator.framework.authorizer.PermissionAuthorizerValve;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.config.Permission;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.config.PermissionAuthorizerConfig;
import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig;
import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig; import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; 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 {
@Override private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkServiceComponent.class);
public void start(BundleContext bundleContext) throws Exception {
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Starting Web Application Authenticator Framework Bundle"); log.debug("Starting Web Application Authenticator Framework Bundle");
} }
try { try {
WebappAuthenticatorConfig.init(); WebappAuthenticatorConfig.init();
WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository(); WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository();
for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) {
WebappAuthenticator authenticator = WebappAuthenticator authenticator =
(WebappAuthenticator) Class.forName(config.getClassName()).newInstance(); (WebappAuthenticator) Class.forName(config.getClassName()).newInstance();
repository.addAuthenticator(authenticator); repository.addAuthenticator(authenticator);
} }
DataHolder.setWebappAuthenticatorRepository(repository); DataHolder.getInstance().setWebappAuthenticatorRepository(repository);
// Adding permissions to registry // Adding permissions to registry
// PermissionAuthorizerConfig.init(); // PermissionAuthorizerConfig.init();
@ -65,7 +71,7 @@ public class WebappAuthenticatorFrameworkBundleActivator implements BundleActiva
// } // }
List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>(); List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>();
valves.add(new WebappAuthenticatorFrameworkValve()); valves.add(new WebappAuthenticationHandler());
valves.add(new PermissionAuthorizerValve()); valves.add(new PermissionAuthorizerValve());
TomcatValveContainer.addValves(valves); TomcatValveContainer.addValves(valves);
@ -77,9 +83,19 @@ public class WebappAuthenticatorFrameworkBundleActivator implements BundleActiva
} }
} }
@Override @SuppressWarnings("unused")
public void stop(BundleContext bundleContext) throws Exception { protected void deactivate(ComponentContext componentContext) {
//do nothing //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);
}
} }

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<CertificateConfigurations> <CertificateConfigurations>
<CertificateKeystore> <CertificateKeystore>
<!-- EMM Keystore file location--> <!-- Certificate Keystore file location-->
<CertificateKeystoreLocation>${carbon.home}/repository/resources/security/wso2cert.jks</CertificateKeystoreLocation> <CertificateKeystoreLocation>${carbon.home}/repository/resources/security/wso2certs.jks</CertificateKeystoreLocation>
<!-- EMM Keystore type (JKS/PKCS12 etc.)--> <!-- Certificate Keystore type (JKS/PKCS12 etc.)-->
<CertificateKeystoreType>JKS</CertificateKeystoreType> <CertificateKeystoreType>JKS</CertificateKeystoreType>
<!-- EMM Keystore password--> <!-- Certificate Keystore password-->
<CertificateKeystorePassword>wso2carbon</CertificateKeystorePassword> <CertificateKeystorePassword>wso2carbon</CertificateKeystorePassword>
<!-- Certificate authority certificate alias --> <!-- Certificate authority certificate alias -->
<CACertAlias>cacert</CACertAlias> <CACertAlias>cacert</CACertAlias>

View File

@ -1,2 +1,3 @@
instructions.configure = \ 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);\ 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);\

View File

@ -382,9 +382,23 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING (
DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
-- POLICY RELATED TABLES FINISHED -- -- POLICY RELATED TABLES FINISHED --
-- NOTIFICATION TABLE --
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
TENANT_ID INTEGER NOT NULL,
STATUS VARCHAR(10) NULL,
DESCRIPTION VARCHAR(100) NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- NOTIFICATION TABLE END --
-- TO:DO - Remove this INSERT sql statement. -- TO:DO - Remove this INSERT sql statement.
--Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android'); --Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android');

View File

@ -37,14 +37,6 @@
<description>This feature contains oauth functionality <description>This feature contains oauth functionality
</description> </description>
<!--<dependencies>-->
<!--<dependency>-->
<!--<groupId>org.wso2.mdm</groupId>-->
<!--<artifactId>dynamic-client-manager</artifactId>-->
<!--</dependency>-->
<!--</dependencies>-->
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -101,8 +93,6 @@
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.wso2.maven</groupId> <groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId> <artifactId>carbon-p2-plugin</artifactId>
@ -123,20 +113,6 @@
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef> <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties> </properties>
</adviceFile> </adviceFile>
<!--<bundles>-->
<!--<bundleDef>-->
<!--org.wso2.carbon.devicemgt:org.wso2.carbon.policy.mgt.core:${carbon.device.mgt.version}-->
<!--</bundleDef>-->
<!--<bundleDef>-->
<!--org.wso2.carbon.devicemgt:org.wso2.carbon.policy.mgt.common:${carbon.device.mgt.version}-->
<!--</bundleDef>-->
<!--<bundleDef>-->
<!--org.wso2.carbon.devicemgt:org.wso2.carbon.simple.policy.decision.point:${carbon.device.mgt.version}-->
<!--</bundleDef>-->
<!--<bundleDef>-->
<!--org.wso2.carbon.devicemgt:org.wso2.carbon.policy.information.point:${carbon.device.mgt.version}-->
<!--</bundleDef>-->
<!--</bundles>-->
<importFeatures> <importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version} <importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef> </importFeatureDef>
@ -145,10 +121,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -4,5 +4,13 @@
<Name>OAuth</Name> <Name>OAuth</Name>
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator</ClassName> <ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator</ClassName>
</Authenticator> </Authenticator>
<Authenticator>
<Name>BasicAuth</Name>
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator</ClassName>
</Authenticator>
<Authenticator>
<Name>JWT</Name>
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator</ClassName>
</Authenticator>
</Authenticators> </Authenticators>
</WebappAuthenticatorConfig> </WebappAuthenticatorConfig>

View File

@ -558,6 +558,11 @@
<artifactId>axis2</artifactId> <artifactId>axis2</artifactId>
<version>${axis2.orbit.version}</version> <version>${axis2.orbit.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>${nimbus.orbit.version}</version>
</dependency>
<!-- End of Orbit dependencies --> <!-- End of Orbit dependencies -->
@ -1251,6 +1256,9 @@
<!-- JSCEP --> <!-- JSCEP -->
<jscep.version>2.0.2.wso2v2</jscep.version> <jscep.version>2.0.2.wso2v2</jscep.version>
<!-- Nimbus Jose-->
<nimbus.orbit.version>2.26.1.wso2v3</nimbus.orbit.version>
</properties> </properties>
</project> </project>