From 796a81311c4bcb74de9c2c6a6b7fe796c149ba34 Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Wed, 13 Jul 2016 14:35:55 +0200 Subject: [PATCH 01/15] Fixed predictable pseudorandom number generator --- .../service/impl/UserManagementServiceImpl.java | 3 ++- .../client/extension/util/JWTClientUtil.java | 17 ++++------------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 0e8d90ffc01..ffad2e8d81a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -37,6 +37,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.URI; import java.net.URISyntaxException; +import java.security.SecureRandom; import java.util.*; @Path("/users") @@ -395,7 +396,7 @@ public class UserManagementServiceImpl implements UserManagementService { String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz"; String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String numericCharset = "0123456789"; - Random randomGenerator = new Random(); + SecureRandom randomGenerator = new SecureRandom(); String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset; int totalCharsetLength = totalCharset.length(); StringBuilder initialUserPassword = new StringBuilder(); diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java index dea0b0754cf..2786b7a00db 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java @@ -36,11 +36,11 @@ import org.apache.http.util.EntityUtils; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.KeyStoreManager; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; @@ -48,24 +48,15 @@ import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.utils.CarbonUtils; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.net.URI; import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; +import java.security.*; import java.security.cert.CertificateException; import java.security.interfaces.RSAPrivateKey; import java.util.Date; import java.util.List; import java.util.Properties; -import java.util.Random; /** * This is the utility class that is used for JWT Client. @@ -210,7 +201,7 @@ public class JWTClientUtil { long nbf = currentTimeMillis + jwtConfig.getValidityPeriodFromCurrentTime() * 60 * 1000; String jti = jwtConfig.getJti(); if (jti == null) { - String defaultTokenId = currentTimeMillis + "" + new Random().nextInt(); + String defaultTokenId = currentTimeMillis + "" + new SecureRandom().nextInt(); jti = defaultTokenId; } List aud = jwtConfig.getAudiences(); From 666506da90d155bdd8a0914caa46d0cb50a5ef64 Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Wed, 13 Jul 2016 15:02:11 +0200 Subject: [PATCH 02/15] Fixed various XML External Entity (XXE) attack vulnerabilities --- .../webapp/publisher/WebappPublisherUtil.java | 2 ++ .../mgt/core/util/CertificateManagerUtil.java | 9 +++------ .../mgt/core/util/ConfigurationUtil.java | 14 +++++++------- .../data/publisher/DataPublisherUtil.java | 2 ++ .../mgt/core/permission/mgt/PermissionUtils.java | 3 ++- .../device/mgt/core/util/DeviceManagerUtil.java | 7 ++----- .../carbon/email/sender/core/EmailSenderUtil.java | 6 ++---- .../policy/mgt/core/util/PolicyManagerUtil.java | 12 ++++-------- .../framework/AuthenticationFrameworkUtil.java | 2 ++ 9 files changed, 26 insertions(+), 31 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java index 9308910c065..17e2edb9a84 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java @@ -20,6 +20,7 @@ package org.wso2.carbon.apimgt.webapp.publisher; import org.w3c.dom.Document; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; @@ -34,6 +35,7 @@ public class WebappPublisherUtil { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); return docBuilder.parse(file); } catch (Exception e) { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java index 9c9d64aa97b..9f75079cfb3 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java @@ -28,28 +28,25 @@ import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import javax.sql.DataSource; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.HashMap; import java.util.Hashtable; import java.util.List; public class CertificateManagerUtil { - private static final Log log = LogFactory.getLog(CertificateManagerUtil.class); - public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String MONITORING_FREQUENCY = "notifierFrequency"; + private static final Log log = LogFactory.getLog(CertificateManagerUtil.class); public static Document convertToDocument(File file) throws CertificateManagementException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new CertificateManagementException("Error occurred while parsing file, while converting " + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java index 36d9182c10b..fa5b49e56cf 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java @@ -21,6 +21,8 @@ import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.xml.sax.SAXException; + +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -48,22 +50,19 @@ public class ConfigurationUtil { public static final String POST_BODY_CA_CAPS = "POSTPKIOperation\nSHA-1\nDES3\n"; public static final String DES_EDE = "DESede"; public static final String CONF_LOCATION = "conf.location"; - private static final String CARBON_HOME = "carbon.home"; - private static final String CERTIFICATE_CONFIG_XML = "certificate-config.xml"; - private static final String CARBON_HOME_ENTRY = "${carbon.home}"; public static final String DEFAULT_PRINCIPAL = "O=WSO2, OU=Mobile, C=LK"; public static final String RSA_PRIVATE_KEY_BEGIN_TEXT = "-----BEGIN RSA PRIVATE KEY-----\n"; public static final String RSA_PRIVATE_KEY_END_TEXT = "-----END RSA PRIVATE KEY-----"; public static final String EMPTY_TEXT = ""; public static final int RSA_KEY_LENGTH = 1024; public static final long MILLI_SECONDS = 1000L * 60 * 60 * 24; - - - private static ConfigurationUtil configurationUtil; + private static final String CARBON_HOME = "carbon.home"; + private static final String CERTIFICATE_CONFIG_XML = "certificate-config.xml"; + private static final String CARBON_HOME_ENTRY = "${carbon.home}"; private static final String[] certificateConfigEntryNames = { CA_CERT_ALIAS, RA_CERT_ALIAS, CERTIFICATE_KEYSTORE, PATH_CERTIFICATE_KEYSTORE, CERTIFICATE_KEYSTORE_PASSWORD, KEYSTORE_CA_CERT_PRIV_PASSWORD, KEYSTORE_RA_CERT_PRIV_PASSWORD }; - + private static ConfigurationUtil configurationUtil; private static Map configMap; private static Map readCertificateConfigurations() throws KeystoreException { @@ -79,6 +78,7 @@ public class ConfigurationUtil { try { File fXmlFile = new File(certConfLocation); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(fXmlFile); } catch (ParserConfigurationException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java index a13310ee942..da430d5fd44 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.analytics.data.publisher; import org.w3c.dom.Document; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; @@ -32,6 +33,7 @@ public class DataPublisherUtil { factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new DataPublisherConfigurationException("Error occurred while parsing file, while converting " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java index d70247f683b..27b95e56ccc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java @@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.core.permission.mgt; import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; @@ -28,6 +27,7 @@ import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; @@ -123,6 +123,7 @@ public class PermissionUtils { factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new PermissionManagementException("Error occurred while parsing file, while converting " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index ec798f2bdc1..a9d472d4985 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -21,7 +21,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; @@ -41,14 +40,11 @@ import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; import javax.sql.DataSource; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.util.*; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; public final class DeviceManagerUtil { @@ -60,6 +56,7 @@ public final class DeviceManagerUtil { factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new DeviceManagementException("Error occurred while parsing file, while converting " + diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.java index c1f03a02bc1..6c34c05805c 100644 --- a/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.java +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.java @@ -19,11 +19,8 @@ package org.wso2.carbon.email.sender.core; import org.w3c.dom.Document; -import org.wso2.carbon.email.sender.core.internal.EmailSenderDataHolder; -import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.carbon.utils.ConfigurationContextService; -import org.wso2.carbon.utils.NetworkUtils; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; @@ -35,6 +32,7 @@ public class EmailSenderUtil { factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new EmailSenderConfigurationFailedException("Error occurred while parsing file, while converting " + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 0d80901d210..ee55646f117 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -44,6 +44,7 @@ import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.Caching; import javax.sql.DataSource; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayOutputStream; @@ -53,17 +54,16 @@ import java.util.*; public class PolicyManagerUtil { - private static final Log log = LogFactory.getLog(PolicyManagerUtil.class); - public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String MONITORING_FREQUENCY = "notifierFrequency"; - + private static final Log log = LogFactory.getLog(PolicyManagerUtil.class); public static Document convertToDocument(File file) throws PolicyManagementException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new PolicyManagementException("Error occurred while parsing file, while converting " + @@ -153,11 +153,7 @@ public class PolicyManagerUtil { public static boolean convertIntToBoolean(int x) { - if (x == 1) { - return true; - } else { - return false; - } + return x == 1; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java index 1ae7b831162..81629eedb5a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java @@ -31,6 +31,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils; import javax.servlet.http.HttpServletResponse; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; @@ -97,6 +98,7 @@ public class AuthenticationFrameworkUtil { factory.setNamespaceAware(true); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return docBuilder.parse(file); } catch (Exception e) { throw new AuthenticatorFrameworkException("Error occurred while parsing file, while converting " + From d28054a39d11d3a894575a2037376e330d980fdf Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Wed, 13 Jul 2016 15:57:12 +0200 Subject: [PATCH 03/15] Made constants real constant using final --- .../carbon/device/mgt/core/search/mgt/Constants.java | 8 ++++---- .../carbon/device/mgt/core/common/TestDataHolder.java | 10 +++++----- .../backend/oauth/OauthAuthenticatorConstants.java | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java index d8b7ada7b4b..0ba5bb7d108 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java @@ -21,8 +21,8 @@ package org.wso2.carbon.device.mgt.core.search.mgt; public class Constants { - public static String GENERAL = "GENERAL"; - public static String PROP_AND = "PROP_AND"; - public static String PROP_OR = "PROP_OR"; - public static String LOCATION = "LOCATION"; + public static final String GENERAL = "GENERAL"; + public static final String PROP_AND = "PROP_AND"; + public static final String PROP_OR = "PROP_OR"; + public static final String LOCATION = "LOCATION"; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java index 3aef2ca2548..bb467761e71 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java @@ -27,13 +27,13 @@ import java.util.Properties; public class TestDataHolder { + public final static String TEST_DEVICE_TYPE = "Test"; + public final static Integer SUPER_TENANT_ID = -1234; + public final static String SUPER_TENANT_DOMAIN = "carbon.super"; + public final static String initialDeviceIdentifier = "12345"; + public final static String OWNER = "admin"; public static Device initialTestDevice; public static DeviceType initialTestDeviceType; - public static String TEST_DEVICE_TYPE = "Test"; - public static Integer SUPER_TENANT_ID = -1234; - public static String SUPER_TENANT_DOMAIN="carbon.super"; - public static String initialDeviceIdentifier = "12345"; - public static String OWNER = "admin"; public static Device generateDummyDeviceData(String deviceType){ diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java index 4c7ace2e6db..66e96101a87 100755 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java +++ b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java @@ -24,6 +24,6 @@ public class OauthAuthenticatorConstants { public static final String BEARER_TOKEN_IDENTIFIER = "token"; public static final String AUTHENTICATOR_NAME = "OAuthAuthenticator"; public static final String SPLITING_CHARACTOR = " "; - public static String OAUTH_ENDPOINT_POSTFIX = + public static final String OAUTH_ENDPOINT_POSTFIX = "/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/"; } From 8a54c5a9cb11be3d826e15ddb88b853fe766c688 Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 15 Jul 2016 11:59:15 +0530 Subject: [PATCH 04/15] Adding emm apis as common modules --- .../devicemgt/api/data-tables-invoker-api.jag | 59 ++++++++ .../jaggeryapps/devicemgt/api/invoker-api.jag | 140 +++++++++--------- .../devicemgt/api/operation-api.jag | 60 ++++++++ .../jaggeryapps/devicemgt/api/policy-api.jag | 52 +++++++ 4 files changed, 238 insertions(+), 73 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag new file mode 100644 index 00000000000..160a7ff517c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag @@ -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. + */ + +var log = new Log("api/data-tables-invoker-api.jag"); + +var uri = request.getRequestURI(); +var uriMatcher = new URIMatcher(String(uri)); + +var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); +var serviceInvokers = require("/app/modules/backend-service-invoker.js")["backendServiceInvoker"]; + +if (uriMatcher.match("/{context}/api/data-tables/invoker")) { + var url = request.getParameter("url"); + var targetURL; + var payload = request.getContent(); + + function appendQueryParam (url, queryParam , value) { + if (url.indexOf("?") > 0) { + return url + "&" + queryParam + "=" + value; + } + return url + "?" + queryParam + "=" + value; + } + targetURL = devicemgtProps["httpsURL"] + request.getParameter("url"); + + var allParams = request.getAllParameters(); + + for (var key in allParams) { + if (allParams.hasOwnProperty(key)) { + if(key == "limit" || key == "offset" || key == "filter"){ + targetURL = appendQueryParam(targetURL, key, allParams[key]); + } + } + } + + serviceInvokers.XMLHttp.get( + targetURL, + // response callback + function (backendResponse) { + response["status"] = backendResponse["status"]; + response["content"] = backendResponse["responseText"]; + } + ); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index ac587def72e..1fd232e3c77 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -17,94 +17,88 @@ * under the License. */ +var log = new Log("api/invoker-api.jag"); + var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); -var log = new Log("api/invoker-api.jag"); - var constants = require("/app/modules/constants.js"); var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); -var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker; - -var result; +var serviceInvokers = require("/app/modules/backend-service-invoker.js")["backendServiceInvoker"]; if (uriMatcher.match("/{context}/api/invoker/execute/")) { - var method = request.getContent().actionMethod; - var targetURL = getTargetUrl(devicemgtProps.httpsURL, request.getContent().actionUrl); - var payload = request.getContent().actionPayload; - var contentType = request.getHeader(constants.CONTENT_TYPE_IDENTIFIER); - var acceptType = request.getHeader(constants.ACCEPT_IDENTIFIER); - if (method == undefined && payload == undefined) { - method = parse(request.getContent()).actionMethod; - targetURL = getTargetUrl(devicemgtProps.httpsURL, parse(request.getContent()).actionUrl); - payload = parse(request.getContent()).actionPayload; + var restAPIRequestDetails = request.getContent(); + + var requestMethod = restAPIRequestDetails["requestMethod"]; + var requestURL = restAPIRequestDetails["requestURL"]; + var requestPayload = restAPIRequestDetails["requestPayload"]; + + if (!requestMethod) { + requestMethod = parse(restAPIRequestDetails)["requestMethod"]; + } + + if (!requestURL) { + requestURL = parse(restAPIRequestDetails)["requestURL"]; } + + if (!requestPayload) { + requestPayload = parse(restAPIRequestDetails)["requestPayload"]; + } + + var restAPIEndpoint = devicemgtProps["httpsURL"] + requestURL; + try { - switch (method) { - case constants.HTTP_GET: - var responseData = serviceInvokers.XMLHttp.get( - targetURL, function (responsePayload) { - response.status = 200; - response.content = responsePayload; - }, - function (responsePayload) { - response.status = responsePayload.status; - response.content = responsePayload.responseText; - }, - contentType, - acceptType); + switch (requestMethod) { + case constants["HTTP_GET"]: + serviceInvokers.XMLHttp.get( + restAPIEndpoint, + function (restAPIResponse) { + response["status"] = restAPIResponse["status"]; + if (restAPIResponse["responseText"]) { + response["content"] = restAPIResponse["responseText"]; + } + } + ); break; - case constants.HTTP_POST: - var responseData = serviceInvokers.XMLHttp.post( - targetURL, payload, function (responsePayload) { - response.status = 200; - response.content = responsePayload; - }, - function (responsePayload) { - response.status = responsePayload.status; - response.content = responsePayload.responseText; - }, - contentType, - acceptType); + case constants["HTTP_POST"]: + serviceInvokers.XMLHttp.post( + restAPIEndpoint, + requestPayload, + function (restAPIResponse) { + response["status"] = restAPIResponse["status"]; + if (restAPIResponse["responseText"]) { + response["content"] = restAPIResponse["responseText"]; + } + } + ); break; - case constants.HTTP_PUT: - var responseData = serviceInvokers.XMLHttp.put( - targetURL, payload, function (responsePayload) { - response.status = 200; - response.content = responsePayload; - }, - function (responsePayload) { - response.status = responsePayload.status; - response.content = responsePayload.responseText; - }, - contentType, - acceptType); + case constants["HTTP_PUT"]: + serviceInvokers.XMLHttp.put( + restAPIEndpoint, + requestPayload, + function (restAPIResponse) { + response["status"] = restAPIResponse["status"]; + if (restAPIResponse["responseText"]) { + response["content"] = restAPIResponse["responseText"]; + } + } + ); break; - case constants.HTTP_DELETE: - var responseData = serviceInvokers.XMLHttp.delete( - targetURL, function (responsePayload) { - response.status = 200; - response.content = responsePayload; - }, - function (responsePayload) { - response.status = responsePayload.status; - response.content = responsePayload.responseText; - }, - contentType, - acceptType); + case constants["HTTP_DELETE"]: + serviceInvokers.XMLHttp.delete( + restAPIEndpoint, + function (restAPIResponse) { + response["status"] = restAPIResponse["status"]; + if (restAPIResponse["responseText"]) { + response["content"] = restAPIResponse["responseText"]; + } + } + ); break; } } catch (e) { - log.error("Exception occurred while accessing sevices", e); + log.error("Exception occurred while trying to access backend " + + "REST API services from Jaggery API invoker layer", e); } } - -function getTargetUrl(serverUrl, actionUrl){ - if(actionUrl == undefined || actionUrl.lastIndexOf("http", 0) === 0){ - return actionUrl; - } else { - return serverUrl + actionUrl; - } -} - %> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag new file mode 100644 index 00000000000..797eac1bd1a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -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. + */ + +var uri = request.getRequestURI(); +var uriMatcher = new URIMatcher(String(uri)); + +var log = new Log("api/operation-api.jag"); + +var serviceInvokers = require("/app/modules/backend-service-invoker.js")["backendServiceInvoker"]; +var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); + +if (uriMatcher.match("/{context}/api/operation/paginate")) { + var deviceType = request.getParameter("deviceType"); + var deviceId = request.getParameter("deviceId"); + var index = request.getParameter("start"); + var length = request.getParameter("length"); + var search = request.getParameter("search[value]"); + + var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices/" + + deviceType + "/" + deviceId + "/operations?offset=" + index + "&limit=" + length; + + serviceInvokers.XMLHttp.get( + restAPIEndpoint, + function (restAPIResponse) { + if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) { + var responsePayload = parse(restAPIResponse["responseText"]); + + var paginatedResult = {}; + paginatedResult["recordsTotal"] = responsePayload["count"]; + paginatedResult["recordsFiltered"] = responsePayload["count"]; + paginatedResult["data"] = responsePayload["operations"]; + + response["status"] = 200; + response["content"] = paginatedResult; + } else { + response["status"] = restAPIResponse["status"]; + if (restAPIResponse["responseText"]) { + response["content"] = parse(restAPIResponse["responseText"]); + } + } + } + ); +} +%> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag new file mode 100644 index 00000000000..d2a2630be7b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag @@ -0,0 +1,52 @@ +<% +/* + * 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. + */ + +/* + @Deprecated + */ + +var uri = request.getRequestURI(); +var uriMatcher = new URIMatcher(String(uri)); + +var log = new Log("api/policy-api.jag"); + +var constants = require("/modules/constants.js"); +var policyModule = require("/modules/policy.js").policyModule; + +var result; +if (uriMatcher.match("/{context}/api/policies/update")) { + payload = request.getContent(); + policyModule.updatePolicyPriorities(payload); +} else if (uriMatcher.match("/{context}/api/policies/{id}/delete")) { + elements = uriMatcher.elements(); + policyId = elements.id; + try { + result = policyModule.deletePolicy(policyId); + } catch (e) { + log.error("Exception occurred while trying to delete policy for id:" + policyId, e); + // http status code 500 refers to - Internal Server Error. + result = 500; + } +} + +// returning the result. +if (result) { + response.content = result; +} +%> \ No newline at end of file From fe489d7f5645918ae97ee8fdbbb90724d59dd451 Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Fri, 15 Jul 2016 09:26:27 +0200 Subject: [PATCH 05/15] Fixed null pointer dereferences --- .../jaxrs/service/impl/PolicyManagementServiceImpl.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index 455dc0f9eaf..487cdc1517d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -28,18 +28,18 @@ import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorization import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyList; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyList; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; -import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -122,7 +122,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { policy.setUsers(policyWrapper.getUsers()); policy.setCompliance(policyWrapper.getCompliance()); //TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here. - List devices = null; + List devices = new ArrayList(); List deviceIdentifiers = policyWrapper.getDeviceIdentifiers(); if (deviceIdentifiers != null) { for (DeviceIdentifier id : deviceIdentifiers) { From 19275634a1e4518b9f651bf87f75e34e6d1d9a16 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 25 Jul 2016 12:04:30 +0530 Subject: [PATCH 06/15] Fixed webapp name resolving issue --- .../lifecycle/util/AnnotationProcessor.java | 36 ++++++-- .../lifecycle/util/ExtendedAnnotationDB.java | 92 +++++++++++++++++++ .../ExtendedFileProtocolIteratorFactory.java | 34 +++++++ .../util/ExtendedIteratorFactory.java | 54 +++++++++++ 4 files changed, 210 insertions(+), 6 deletions(-) create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index a88fe00e9fe..3db6a31551c 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -36,11 +36,14 @@ import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementExcept import javax.servlet.ServletContext; import javax.ws.rs.*; +import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; @@ -85,16 +88,13 @@ public class AnnotationProcessor { * @throws IOException */ public Set scanStandardContext(String className) throws IOException { - AnnotationDB db = new AnnotationDB(); + ExtendedAnnotationDB db = new ExtendedAnnotationDB(); db.addIgnoredPackages(PACKAGE_ORG_APACHE); db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); - URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext); - URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext); - URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath); - - db.scanArchives(urls); + URL classPath = findWebInfClassesPath(servletContext); + db.scanArchives(classPath); //Returns a list of classes with given Annotation return db.getAnnotationIndex().get(className); @@ -387,4 +387,28 @@ public class AnnotationProcessor { } } + /** + * Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with IteratorFactory + * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory + * + * @param servletContext + * @return null if cannot determin /WEB-INF/classes + */ + public static URL findWebInfClassesPath(ServletContext servletContext) + { + String path = servletContext.getRealPath("/WEB-INF/classes"); + if (path == null) return null; + File fp = new File(path); + if (fp.exists() == false) return null; + try + { + URI uri = fp.toURI(); + return uri.toURL(); + } + catch (MalformedURLException e) + { + throw new RuntimeException(e); + } + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java new file mode 100644 index 00000000000..24fdd738b87 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; + +import org.scannotation.AnnotationDB; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.StreamIterator; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +public class ExtendedAnnotationDB extends AnnotationDB { + + public ExtendedAnnotationDB() { + super(); + } + + public void scanArchives(URL... urls) throws IOException { + URL[] arr$ = urls; + int len$ = urls.length; + + for(int i$ = 0; i$ < len$; ++i$) { + URL url = arr$[i$]; + Filter filter = new Filter() { + public boolean accepts(String filename) { + if(filename.endsWith(".class")) { + if(filename.startsWith("/") || filename.startsWith("\\")) { + filename = filename.substring(1); + } + + if(!ExtendedAnnotationDB.this.ignoreScan(filename.replace('/', '.'))) { + return true; + } + } + return false; + } + }; + StreamIterator it = ExtendedIteratorFactory.create(url, filter); + + InputStream stream; + while((stream = it.next()) != null) { + this.scanClass(stream); + } + } + + } + + private boolean ignoreScan(String intf) { + String[] arr$; + int len$; + int i$; + String ignored; + if(this.scanPackages != null) { + arr$ = this.scanPackages; + len$ = arr$.length; + + for(i$ = 0; i$ < len$; ++i$) { + ignored = arr$[i$]; + if(intf.startsWith(ignored + ".")) { + return false; + } + } + + return true; + } else { + arr$ = this.ignoredPackages; + len$ = arr$.length; + + for(i$ = 0; i$ < len$; ++i$) { + ignored = arr$[i$]; + if(intf.startsWith(ignored + ".")) { + return true; + } + } + return false; + } + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java new file mode 100644 index 00000000000..34936f61c8c --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; + +import org.scannotation.archiveiterator.*; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +public class ExtendedFileProtocolIteratorFactory implements DirectoryIteratorFactory { + + private static final String ENCODING_SCHEME = "UTF-8"; + + @Override + public StreamIterator create(URL url, Filter filter) throws IOException { + File f = new File(java.net.URLDecoder.decode(url.getPath(), ENCODING_SCHEME)); + return f.isDirectory()?new FileIterator(f, filter):new JarIterator(url.openStream(), filter); + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java new file mode 100644 index 00000000000..a62a58f7333 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; + +import org.scannotation.archiveiterator.DirectoryIteratorFactory; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.JarIterator; +import org.scannotation.archiveiterator.StreamIterator; + +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; + +public class ExtendedIteratorFactory { + + private static final ConcurrentHashMap registry = new ConcurrentHashMap(); + + public static StreamIterator create(URL url, Filter filter) throws IOException { + String urlString = url.toString(); + if(urlString.endsWith("!/")) { + urlString = urlString.substring(4); + urlString = urlString.substring(0, urlString.length() - 2); + url = new URL(urlString); + } + + if(!urlString.endsWith("/")) { + return new JarIterator(url.openStream(), filter); + } else { + DirectoryIteratorFactory factory = registry.get(url.getProtocol()); + if(factory == null) { + throw new IOException("Unable to scan directory of protocol: " + url.getProtocol()); + } else { + return factory.create(url, filter); + } + } + } + + static { + registry.put("file", new ExtendedFileProtocolIteratorFactory()); + } +} From 7facff4b58210a269b9fc884be7605ca7c8461a7 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 25 Jul 2016 15:28:41 +0530 Subject: [PATCH 07/15] Updating ui init logic --- .../main/resources/jaggeryapps/devicemgt/app/modules/init.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js index 897a4f0c4ff..35c902dbab4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js @@ -31,4 +31,4 @@ var permissions = { '/permission/admin/device-mgt/user': ['ui.execute'], '/permission/admin/manage/api/subscribe': ['ui.execute'] }; -userModule.addRole("internal/devicemgt-user", ["admin"], permissions); +//userModule.addRole("internal/devicemgt-user", ["admin"], permissions); From 87dbb5f9e14dd8b753614d55494ff3232b2b9362 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 25 Jul 2016 15:32:39 +0530 Subject: [PATCH 08/15] Refactoring ui token handling functions --- .../devicemgt/app/modules/api-wrapper-util.js | 73 ++++++++++--------- .../app/modules/invoker-request-wrapper.js | 2 +- 2 files changed, 41 insertions(+), 34 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js index 55d80f54970..1a2f7be25f2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js @@ -1,55 +1,62 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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 + * "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. */ var apiWrapperUtil = function () { - var module = {}; - var tokenUtil = require("/app/modules/util.js").util; + // var log = new Log("/app/modules/api-wrapper-util.js"); + + var tokenUtil = require("/app/modules/util.js")["util"]; var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var log = new Log("/app/modules/api-wrapper-util.js"); - module.refreshToken = function () { - var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); - var clientData = session.get(constants.ENCODED_CLIENT_KEYS_IDENTIFIER); - tokenPair = tokenUtil.refreshToken(tokenPair, clientData); - session.put(constants.ACCESS_TOKEN_PAIR_IDENTIFIER, tokenPair); + var publicMethods = {}; + + publicMethods.refreshToken = function () { + var accessTokenPair = session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]); + // accessTokenPair includes current access token as well as current refresh token + var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); + accessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials); + session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], accessTokenPair); }; - module.setupAccessTokenPair = function (type, properties) { - var tokenPair; - var clientData = tokenUtil.getDyanmicCredentials(properties); - var jwtToken = tokenUtil.getTokenWithJWTGrantType(clientData); - clientData = tokenUtil.getTenantBasedAppCredentials(properties.username, jwtToken); - var encodedClientKeys = tokenUtil.encode(clientData.clientId + ":" + clientData.clientSecret); - session.put(constants.ENCODED_CLIENT_KEYS_IDENTIFIER, encodedClientKeys); - if (type == constants.GRANT_TYPE_PASSWORD) { - var scopes = devicemgtProps.scopes; - var scope = ""; - scopes.forEach(function(entry) { - scope += entry + " "; - }); - tokenPair = - tokenUtil.getTokenWithPasswordGrantType(properties.username, encodeURIComponent(properties.password), - encodedClientKeys, scope); - } else if (type == constants.GRANT_TYPE_SAML) { - tokenPair = tokenUtil. - getTokenWithSAMLGrantType(properties.samlToken, encodedClientKeys, "PRODUCTION"); + + publicMethods.setupAccessTokenPair = function (type, properties) { + var dynamicClientCredentials = tokenUtil.getDyanmicCredentials(properties); + var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials); + var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(properties["username"], jwtToken); + var encodedTenantBasedClientCredentials = tokenUtil. + encode(tenantBasedClientCredentials["clientId"] + ":" + tenantBasedClientCredentials["clientSecret"]); + + session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials); + + var accessTokenPair; + // accessTokenPair will include current access token as well as current refresh token + if (type == constants["GRANT_TYPE_PASSWORD"]) { + var arrayOfScopes = devicemgtProps["scopes"]; + var stringOfScopes = ""; + arrayOfScopes.forEach(function (entry) { stringOfScopes += entry + " "; }); + accessTokenPair = tokenUtil.getTokenWithPasswordGrantType(properties["username"], + encodeURIComponent(properties["password"]), encodedTenantBasedClientCredentials, stringOfScopes); + } else if (type == constants["GRANT_TYPE_SAML"]) { + accessTokenPair = tokenUtil.getTokenWithSAMLGrantType(properties["samlToken"], + encodedTenantBasedClientCredentials, "PRODUCTION"); } - session.put(constants.ACCESS_TOKEN_PAIR_IDENTIFIER, tokenPair); + + session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], accessTokenPair); }; - return module; + + return publicMethods; }(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js index b4ccc62dc1f..d191b1868dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js @@ -17,7 +17,7 @@ */ /* - @Deprecated + @Deprecated - new */ /** From 3457bba4a3386097f077c7b4554f02440a3f3b4c Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 25 Jul 2016 19:21:08 +0530 Subject: [PATCH 09/15] Adding Annotation reading fix for device-mgt-extensions --- .../pom.xml | 11 ++- .../feature/mgt/util/AnnotationProcessor.java | 36 +++++++- .../mgt/util/ExtendedAnnotationDB.java | 92 +++++++++++++++++++ .../ExtendedFileProtocolIteratorFactory.java | 34 +++++++ .../mgt/util/ExtendedIteratorFactory.java | 54 +++++++++++ 5 files changed, 221 insertions(+), 6 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedAnnotationDB.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedFileProtocolIteratorFactory.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedIteratorFactory.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 12315343eb2..c141804a98d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -111,6 +111,14 @@ org.wso2.carbon.analytics-common org.wso2.carbon.event.output.adapter.core + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl + @@ -148,7 +156,8 @@ javax.xml.*;resolution:=optional, org.apache.commons.lang, javax.ws.rs;version="0.0.0";resolution:=optional, - org.scannotation + org.scannotation, + org.scannotation.archiveiterator diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationProcessor.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationProcessor.java index 2819d47ee1f..43d68f0f2e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationProcessor.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationProcessor.java @@ -38,11 +38,14 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; +import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; @@ -80,14 +83,13 @@ public class AnnotationProcessor { * Scan the context for classes with annotations */ public Set scanStandardContext(String className) throws IOException { - AnnotationDB db = new AnnotationDB(); + ExtendedAnnotationDB db = new ExtendedAnnotationDB(); db.addIgnoredPackages(PACKAGE_ORG_APACHE); db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); - URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext); - URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext); - URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath); - db.scanArchives(urls); + + URL classPath = findWebInfClassesPath(servletContext); + db.scanArchives(classPath); //Returns a list of classes with given Annotation return db.getAnnotationIndex().get(className); @@ -276,4 +278,28 @@ public class AnnotationProcessor { return null; } } + + /** + * Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with IteratorFactory + * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory + * + * @param servletContext + * @return null if cannot determin /WEB-INF/classes + */ + public static URL findWebInfClassesPath(ServletContext servletContext) + { + String path = servletContext.getRealPath("/WEB-INF/classes"); + if (path == null) return null; + File fp = new File(path); + if (fp.exists() == false) return null; + try + { + URI uri = fp.toURI(); + return uri.toURL(); + } + catch (MalformedURLException e) + { + throw new RuntimeException(e); + } + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedAnnotationDB.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedAnnotationDB.java new file mode 100644 index 00000000000..5d9c55ed06d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedAnnotationDB.java @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.extensions.feature.mgt.util; + +import org.scannotation.AnnotationDB; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.StreamIterator; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +public class ExtendedAnnotationDB extends AnnotationDB { + + public ExtendedAnnotationDB() { + super(); + } + + public void scanArchives(URL... urls) throws IOException { + URL[] arr$ = urls; + int len$ = urls.length; + + for(int i$ = 0; i$ < len$; ++i$) { + URL url = arr$[i$]; + Filter filter = new Filter() { + public boolean accepts(String filename) { + if(filename.endsWith(".class")) { + if(filename.startsWith("/") || filename.startsWith("\\")) { + filename = filename.substring(1); + } + + if(!ExtendedAnnotationDB.this.ignoreScan(filename.replace('/', '.'))) { + return true; + } + } + return false; + } + }; + StreamIterator it = ExtendedIteratorFactory.create(url, filter); + + InputStream stream; + while((stream = it.next()) != null) { + this.scanClass(stream); + } + } + + } + + private boolean ignoreScan(String intf) { + String[] arr$; + int len$; + int i$; + String ignored; + if(this.scanPackages != null) { + arr$ = this.scanPackages; + len$ = arr$.length; + + for(i$ = 0; i$ < len$; ++i$) { + ignored = arr$[i$]; + if(intf.startsWith(ignored + ".")) { + return false; + } + } + + return true; + } else { + arr$ = this.ignoredPackages; + len$ = arr$.length; + + for(i$ = 0; i$ < len$; ++i$) { + ignored = arr$[i$]; + if(intf.startsWith(ignored + ".")) { + return true; + } + } + return false; + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedFileProtocolIteratorFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedFileProtocolIteratorFactory.java new file mode 100644 index 00000000000..6ee0cc7c008 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedFileProtocolIteratorFactory.java @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.extensions.feature.mgt.util; + +import org.scannotation.archiveiterator.*; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +public class ExtendedFileProtocolIteratorFactory implements DirectoryIteratorFactory { + + private static final String ENCODING_SCHEME = "UTF-8"; + + @Override + public StreamIterator create(URL url, Filter filter) throws IOException { + File f = new File(java.net.URLDecoder.decode(url.getPath(), ENCODING_SCHEME)); + return f.isDirectory()?new FileIterator(f, filter):new JarIterator(url.openStream(), filter); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedIteratorFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedIteratorFactory.java new file mode 100644 index 00000000000..0845ff83e33 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/ExtendedIteratorFactory.java @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.extensions.feature.mgt.util; + +import org.scannotation.archiveiterator.DirectoryIteratorFactory; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.JarIterator; +import org.scannotation.archiveiterator.StreamIterator; + +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; + +public class ExtendedIteratorFactory { + + private static final ConcurrentHashMap registry = new ConcurrentHashMap(); + + public static StreamIterator create(URL url, Filter filter) throws IOException { + String urlString = url.toString(); + if(urlString.endsWith("!/")) { + urlString = urlString.substring(4); + urlString = urlString.substring(0, urlString.length() - 2); + url = new URL(urlString); + } + + if(!urlString.endsWith("/")) { + return new JarIterator(url.openStream(), filter); + } else { + DirectoryIteratorFactory factory = registry.get(url.getProtocol()); + if(factory == null) { + throw new IOException("Unable to scan directory of protocol: " + url.getProtocol()); + } else { + return factory.create(url, filter); + } + } + } + + static { + registry.put("file", new ExtendedFileProtocolIteratorFactory()); + } +} From d05c6e2170790e655b3ca1b48f1767867c3bcc84 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 25 Jul 2016 22:23:22 +0530 Subject: [PATCH 10/15] Deprecating /api/token.jag (unused) --- .../resources/jaggeryapps/devicemgt/api/token.jag | 11 ++++++++--- .../main/resources/jaggeryapps/devicemgt/jaggery.conf | 4 ---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag index d2385582da8..b3302a66596 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag @@ -16,7 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -var apiWrapperUtil = require("/app/modules/api-wrapper-util.js").apiWrapperUtil; -var tokenCookie = apiWrapperUtil.refreshToken(); -print(tokenCookie); + +/* + @Deprecated - new + */ + +// var apiWrapperUtil = require("/app/modules/api-wrapper-util.js").apiWrapperUtil; +// var tokenCookie = apiWrapperUtil.refreshToken(); +// print(tokenCookie); %> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/jaggery.conf b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/jaggery.conf index 909af4c4569..83971215679 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/jaggery.conf +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/jaggery.conf @@ -19,10 +19,6 @@ "url": "/api/user/*", "path": "/api/user-api.jag" }, - { - "url": "/token", - "path": "/api/token-api.jag" - }, { "url": "/api/invoker/*", "path": "/api/invoker-api.jag" From a02f7a5db11508bbe5e24c911663e3a2dccdd32d Mon Sep 17 00:00:00 2001 From: hasuniea Date: Tue, 26 Jul 2016 10:21:25 +0530 Subject: [PATCH 11/15] fixing formatting issue --- .../api/beans/EnrollmentCertificate.java | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java index a687a259bb1..e119746c911 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/EnrollmentCertificate.java @@ -1,8 +1,23 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; -/** - * Created by hasunie on 5/26/16. - */ public class EnrollmentCertificate { String serial; String pem; From b72d0996418ba579cea86077efd0d150b7ad928e Mon Sep 17 00:00:00 2001 From: dilanua Date: Tue, 26 Jul 2016 11:14:46 +0530 Subject: [PATCH 12/15] Refactoring oauth token handling functions --- .../devicemgt/app/modules/api-wrapper-util.js | 123 ++++++++++++++---- 1 file changed, 98 insertions(+), 25 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js index 1a2f7be25f2..0db3225031f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js @@ -17,45 +17,118 @@ */ var apiWrapperUtil = function () { - // var log = new Log("/app/modules/api-wrapper-util.js"); + var log = new Log("/app/modules/api-wrapper-util.js"); var tokenUtil = require("/app/modules/util.js")["util"]; var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var privateMethods = {}; var publicMethods = {}; + privateMethods.setUpEncodedTenantBasedClientCredentials = function (username) { + if (!username) { + log.error("Could not set up encoded tenant based client credentials " + + "to session context. No username is found as input."); + } else { + var dynamicClientCredentials = tokenUtil.getDyanmicClientCredentials(); + if (!dynamicClientCredentials) { + log.error("Could not set up encoded tenant based client credentials " + + "to session context as the server is unable to obtain dynamic client credentials."); + } else { + var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials); + if (!jwtToken) { + log.error("Could not set up encoded tenant based client credentials " + + "to session context as the server is unable to obtain a jwt token."); + } else { + var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(username, jwtToken); + if (!tenantBasedClientCredentials) { + log.error("Could not set up encoded tenant based client credentials " + + "to session context as the server is unable to obtain such credentials."); + } else { + var encodedTenantBasedClientCredentials = + tokenUtil.encode(tenantBasedClientCredentials["clientId"] + ":" + + tenantBasedClientCredentials["clientSecret"]); + // setting up encoded tenant based client credentials to session context. + session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials); + } + } + } + } + }; + publicMethods.refreshToken = function () { - var accessTokenPair = session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]); + var accessTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"])); // accessTokenPair includes current access token as well as current refresh token var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - accessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials); - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], accessTokenPair); + if (!accessTokenPair || !encodedClientCredentials) { + log.error("Error in refreshing tokens. Either the access token pair, " + + "encoded client credentials or both input are not found under session context."); + } else { + var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials); + if (!newAccessTokenPair) { + log.error("Error in refreshing tokens. Unable to update " + + "session context with new access token pair."); + } else { + session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newAccessTokenPair)); + } + } }; - publicMethods.setupAccessTokenPair = function (type, properties) { - var dynamicClientCredentials = tokenUtil.getDyanmicCredentials(properties); - var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials); - var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(properties["username"], jwtToken); - var encodedTenantBasedClientCredentials = tokenUtil. - encode(tenantBasedClientCredentials["clientId"] + ":" + tenantBasedClientCredentials["clientSecret"]); - - session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials); - - var accessTokenPair; - // accessTokenPair will include current access token as well as current refresh token - if (type == constants["GRANT_TYPE_PASSWORD"]) { - var arrayOfScopes = devicemgtProps["scopes"]; - var stringOfScopes = ""; - arrayOfScopes.forEach(function (entry) { stringOfScopes += entry + " "; }); - accessTokenPair = tokenUtil.getTokenWithPasswordGrantType(properties["username"], - encodeURIComponent(properties["password"]), encodedTenantBasedClientCredentials, stringOfScopes); - } else if (type == constants["GRANT_TYPE_SAML"]) { - accessTokenPair = tokenUtil.getTokenWithSAMLGrantType(properties["samlToken"], - encodedTenantBasedClientCredentials, "PRODUCTION"); + publicMethods.setupAccessTokenPairByPasswordGrantType = function (username, password) { + if (!username || !password) { + log.error("Could not set up access token pair by password grant type. " + + "Either username, password or both are missing as input."); + } else { + privateMethods.setUpEncodedTenantBasedClientCredentials(username); + var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); + if (!encodedClientCredentials) { + log.error("Could not set up access token pair by password grant type. " + + "Encoded client credentials are missing."); + } else { + var accessTokenPair; + // accessTokenPair will include current access token as well as current refresh token + var arrayOfScopes = devicemgtProps["scopes"]; + var stringOfScopes = ""; + arrayOfScopes.forEach(function (entry) { + stringOfScopes += entry + " "; + }); + accessTokenPair = tokenUtil. + getTokenWithPasswordGrantType(username, + encodeURIComponent(password), encodedClientCredentials, stringOfScopes); + if (!accessTokenPair) { + log.error("Could not set up access token pair by password grant type. Error in token retrieval."); + } else { + // setting up access token pair into session context as a string + session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair)); + } + } } + }; - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], accessTokenPair); + publicMethods.setupAccessTokenPairBySamlGrantType = function (username, samlToken) { + if (!username || !samlToken) { + log.error("Could not set up access token pair by saml grant type. " + + "Either username, samlToken or both are missing as input."); + } else { + privateMethods.setUpEncodedTenantBasedClientCredentials(username); + var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); + if (!encodedClientCredentials) { + log.error("Could not set up access token pair by saml grant type. " + + "Encoded client credentials are missing."); + } else { + var accessTokenPair; + // accessTokenPair will include current access token as well as current refresh token + accessTokenPair = tokenUtil. + getTokenWithSAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); + if (!accessTokenPair) { + log.error("Could not set up access token pair by password grant type. Error in token retrieval."); + } else { + // setting up access token pair into session context as a string + session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair)); + } + } + } }; return publicMethods; From bd1322e8014d51965aef513377ff3381e0b60e4e Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 26 Jul 2016 11:28:31 +0530 Subject: [PATCH 13/15] Improving transaction handling in certificate management component and cleaning up the OperationManagerImpl --- ...CertificateManagementAdminServiceImpl.java | 8 +- .../mgt/core/dao/CertificateDAO.java | 15 +- .../dao/CertificateManagementDAOFactory.java | 25 +- .../mgt/core/impl/CertificateGenerator.java | 8 +- .../mgt/core/impl/KeyStoreReader.java | 64 +- .../service/CertificateManagementService.java | 17 +- .../CertificateManagementServiceImpl.java | 76 +- .../operation/mgt/OperationManagerImpl.java | 673 +++++++++--------- .../device/mgt/core/Search/util/Utils.java | 1 - 9 files changed, 474 insertions(+), 413 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java index 15b0a548c75..6d98253f83b 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java @@ -9,8 +9,8 @@ import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificat import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil; -import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -76,7 +76,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem try { certificateResponse = certificateService.searchCertificates(serialNumber); return Response.status(Response.Status.OK).entity(certificateResponse).build(); - } catch (CertificateManagementDAOException e) { + } catch (CertificateManagementException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; log.error(msg, e); throw new UnexpectedServerErrorException( @@ -106,7 +106,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem certificates.setCount(result.getRecordsTotal()); certificates.setList((List) result.getData()); return Response.status(Response.Status.OK).entity(certificates).build(); - } catch (CertificateManagementDAOException e) { + } catch (CertificateManagementException e) { String msg = "Error occurred while fetching all certificates."; log.error(msg, e); throw new UnexpectedServerErrorException( @@ -128,7 +128,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem } return Response.status(Response.Status.OK).entity("Certificate that carries the serial number '" + serialNumber + "' has been removed").build(); - } catch (CertificateManagementDAOException e) { + } catch (CertificateManagementException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; log.error(msg, e); throw new UnexpectedServerErrorException( diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java index 5916148c228..1895c14491f 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java @@ -18,11 +18,11 @@ package org.wso2.carbon.certificate.mgt.core.dao; +import org.wso2.carbon.certificate.mgt.core.bean.Certificate; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; -import java.io.ByteArrayInputStream; import java.util.List; /** @@ -37,8 +37,9 @@ public interface CertificateDAO { * * @param certificate Holds the certificate and relevant details. * @throws CertificateManagementDAOException + * */ - void addCertificate(List certificate) + void addCertificate(List certificate) throws CertificateManagementDAOException; /** @@ -47,31 +48,37 @@ public interface CertificateDAO { * @param serialNumber Serial number of the certificate. * @return representation of the certificate. * @throws CertificateManagementDAOException + * */ - org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse retrieveCertificate(String serialNumber - ) throws CertificateManagementDAOException; + CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementDAOException; /** * Get all the certificates in a paginated manner. + * * @param request Request mentioning pagination details such as length and stating index. * @return Pagination result with data and the count of results. * @throws CertificateManagementDAOException + * */ PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementDAOException; /** * Get all the certificates. + * * @return List of certificates * @throws CertificateManagementDAOException + * */ public List getAllCertificates() throws CertificateManagementDAOException; /** * Delete a certificate identified by a serial number() + * * @param serialNumber serial number * @return whether the certificate was removed or not. */ boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; public List searchCertificate(String serialNumber) throws CertificateManagementDAOException; + } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java index cfe65cdb7b3..02345c127b0 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java @@ -50,7 +50,7 @@ public class CertificateManagementDAOFactory { try { databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection", e); + log.error( "Error occurred while retrieving config.datasource connection", e); } } @@ -59,7 +59,7 @@ public class CertificateManagementDAOFactory { try { databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection", e); + log.error("Error occurred while retrieving a datasource connection", e); } } @@ -72,11 +72,22 @@ public class CertificateManagementDAOFactory { } try { conn = dataSource.getConnection(); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving a data source connection", e); + } + + try { conn.setAutoCommit(false); - currentConnection.set(conn); } catch (SQLException e) { - throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + try { + conn.close(); + } catch (SQLException e1) { + log.warn("Error occurred while closing the borrowed connection. " + + "Transaction has ended pre-maturely", e1); + } + throw new TransactionManagementException("Error occurred while setting auto-commit to false", e); } + currentConnection.set(conn); } public static void openConnection() throws SQLException { @@ -111,6 +122,8 @@ public class CertificateManagementDAOFactory { conn.commit(); } catch (SQLException e) { log.error("Error occurred while committing the transaction", e); + } finally { + closeConnection(); } } @@ -125,6 +138,8 @@ public class CertificateManagementDAOFactory { conn.rollback(); } catch (SQLException e) { log.warn("Error occurred while roll-backing the transaction", e); + } finally { + closeConnection(); } } @@ -138,7 +153,7 @@ public class CertificateManagementDAOFactory { try { conn.close(); } catch (SQLException e) { - log.warn("Error occurred while close the connection"); + log.warn("Error occurred while close the connection", e); } currentConnection.remove(); } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index f71162904c4..e4332c599f9 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -674,10 +674,7 @@ public class CertificateGenerator { } catch (TransactionManagementException e) { String errorMsg = "Error occurred when saving the generated certificate"; log.error(errorMsg, e); - CertificateManagementDAOFactory.rollbackTransaction(); throw new KeystoreException(errorMsg, e); - } finally { - CertificateManagementDAOFactory.closeConnection(); } } @@ -738,9 +735,8 @@ public class CertificateGenerator { } catch (IOException e) { throw new KeystoreException("CSR cannot be recovered.", e); } - X509Certificate signedCertificate = generateCertificateFromCSR(privateKeyCA, certificationRequest, - certCA.getIssuerX500Principal().getName()); - return signedCertificate; + return generateCertificateFromCSR(privateKeyCA, certificationRequest, + certCA.getIssuerX500Principal().getName()); } public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java index c7d5978fa67..3faf94abb96 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java @@ -19,6 +19,7 @@ package org.wso2.carbon.certificate.mgt.core.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; @@ -41,17 +42,21 @@ public class KeyStoreReader { private static final Log log = LogFactory.getLog(KeyStoreReader.class); - private KeyStore loadKeyStore(String configEntryKeyStoreType, String configEntryKeyStorePath, - String configEntryKeyStorePassword) throws KeystoreException { + private CertificateDAO certDao; - InputStream inputStream = null; - KeyStore keystore; + public KeyStoreReader() { + this.certDao = CertificateManagementDAOFactory.getCertificateDAO(); + } + private KeyStore loadKeyStore( + String configEntryKeyStoreType, String configEntryKeyStorePath, + String configEntryKeyStorePassword) throws KeystoreException { + InputStream is = null; + KeyStore keystore; try { keystore = KeyStore.getInstance(ConfigurationUtil.getConfigEntry(configEntryKeyStoreType)); - inputStream = new FileInputStream(ConfigurationUtil.getConfigEntry(configEntryKeyStorePath)); - keystore.load(inputStream, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray()); - + is = new FileInputStream(ConfigurationUtil.getConfigEntry(configEntryKeyStorePath)); + keystore.load(is, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when loading KeyStore"; log.error(errorMsg, e); @@ -74,8 +79,8 @@ public class KeyStoreReader { throw new KeystoreException(errorMsg, e); } finally { try { - if (inputStream != null) { - inputStream.close(); + if (is != null) { + is.close(); } } catch (IOException e) { log.error("Error closing KeyStore input stream", e); @@ -86,16 +91,12 @@ public class KeyStoreReader { } private synchronized void saveKeyStore(KeyStore keyStore, String configEntryKeyStorePath, - String configEntryKeyStorePassword) throws KeystoreException { - - FileOutputStream outputStream = null; - + String configEntryKeyStorePassword) throws KeystoreException { + FileOutputStream os = null; try { - outputStream = new FileOutputStream( + os = new FileOutputStream( ConfigurationUtil.getConfigEntry(configEntryKeyStorePath)); - keyStore.store(outputStream, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray()); - outputStream.close(); - + keyStore.store(os, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when loading KeyStore"; log.error(errorMsg, e); @@ -118,8 +119,8 @@ public class KeyStoreReader { throw new KeystoreException(errorMsg, e); } finally { try { - if (outputStream != null) { - outputStream.close(); + if (os != null) { + os.close(); } } catch (IOException e) { log.error("Error closing KeyStore output stream", e); @@ -139,10 +140,8 @@ public class KeyStoreReader { } public Certificate getCACertificate() throws KeystoreException { - KeyStore keystore = loadCertificateKeyStore(); Certificate caCertificate; - try { caCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.CA_CERT_ALIAS)); } catch (KeyStoreException e) { @@ -188,7 +187,6 @@ public class KeyStoreReader { } public Certificate getRACertificate() throws KeystoreException { - KeyStore keystore = loadCertificateKeyStore(); Certificate raCertificate; try { @@ -207,13 +205,11 @@ public class KeyStoreReader { } public Certificate getCertificateByAlias(String alias) throws KeystoreException { - Certificate raCertificate = null; try { CertificateManagementDAOFactory.openConnection(); - CertificateResponse certificateResponse = CertificateManagementDAOFactory.getCertificateDAO(). - retrieveCertificate(alias); - if(certificateResponse != null) { + CertificateResponse certificateResponse = certDao.retrieveCertificate(alias); + if (certificateResponse != null) { raCertificate = (Certificate) Serializer.deserialize(certificateResponse.getCertificate()); } } catch (CertificateManagementDAOException e) { @@ -221,7 +217,7 @@ public class KeyStoreReader { log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (ClassNotFoundException | IOException e) { - String errorMsg = "Error when deserializing saved certificate."; + String errorMsg = "Error when de-serializing saved certificate."; log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (SQLException e) { @@ -234,8 +230,7 @@ public class KeyStoreReader { return raCertificate; } - PrivateKey getRAPrivateKey() throws KeystoreException { - + public PrivateKey getRAPrivateKey() throws KeystoreException { KeyStore keystore = loadCertificateKeyStore(); PrivateKey raPrivateKey; try { @@ -264,13 +259,11 @@ public class KeyStoreReader { } public CertificateResponse getCertificateBySerial(String serialNumber) throws KeystoreException { - CertificateResponse certificateResponse = null; try { CertificateManagementDAOFactory.openConnection(); - certificateResponse = CertificateManagementDAOFactory.getCertificateDAO(). - retrieveCertificate(serialNumber); - if(certificateResponse != null && certificateResponse.getCertificate() != null) { + certificateResponse = certDao.retrieveCertificate(serialNumber); + if (certificateResponse != null && certificateResponse.getCertificate() != null) { Certificate certificate = (Certificate) Serializer.deserialize(certificateResponse.getCertificate()); if (certificate instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) certificate; @@ -278,10 +271,9 @@ public class KeyStoreReader { certificateResponse.setCommonName(commonName); } } - } catch (CertificateManagementDAOException e) { String errorMsg = "Error when retrieving certificate from the the database for the serial number: " + - serialNumber; + serialNumber; log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (SQLException e) { @@ -289,7 +281,7 @@ public class KeyStoreReader { log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (ClassNotFoundException | IOException e) { - String errorMsg = "Error when deserializing saved certificate."; + String errorMsg = "Error when de-serializing saved certificate."; log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } finally { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java index d294dbc224d..04d4c8c35f1 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java @@ -18,7 +18,7 @@ package org.wso2.carbon.certificate.mgt.core.service; import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; @@ -47,8 +47,8 @@ public interface CertificateManagementService { byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException; - X509Certificate generateCertificateFromCSR(PrivateKey privateKey, PKCS10CertificationRequest request, - String issueSubject) throws KeystoreException; + X509Certificate generateCertificateFromCSR( + PrivateKey privateKey, PKCS10CertificationRequest request, String issueSubject) throws KeystoreException; Certificate getCertificateByAlias(String alias) throws KeystoreException; @@ -71,13 +71,14 @@ public interface CertificateManagementService { public X509Certificate pemToX509Certificate(String pem) throws KeystoreException; - public CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementDAOException; + public CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException; - public PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementDAOException; + public PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementException; - boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; + boolean removeCertificate(String serialNumber) throws CertificateManagementException; - public List getCertificates() throws CertificateManagementDAOException; + public List getCertificates() throws CertificateManagementException; + + public List searchCertificates(String serialNumber) throws CertificateManagementException; - public List searchCertificates(String serialNumber) throws CertificateManagementDAOException; } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 875704784db..26902e7248f 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -25,6 +25,7 @@ import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOExceptio import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; +import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; import org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader; @@ -51,7 +52,6 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } public static CertificateManagementServiceImpl getInstance() { - if (certificateManagementServiceImpl == null) { certificateManagementServiceImpl = new CertificateManagementServiceImpl(); keyStoreReader = new KeyStoreReader(); @@ -106,7 +106,8 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe return certificateGenerator.verifyPEMSignature(requestCertificate); } - @Override public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException { + @Override + public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException { return certificateGenerator.verifyCertificateDN(requestDN); } @@ -135,39 +136,47 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe return certificateGenerator.pemToX509Certificate(pem); } - public CertificateResponse retrieveCertificate(String serialNumber) - throws CertificateManagementDAOException { + public CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException { CertificateDAO certificateDAO; try { CertificateManagementDAOFactory.openConnection(); certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); return certificateDAO.retrieveCertificate(serialNumber); } catch (SQLException e) { - String errorMsg = "Error when opening connection"; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); + String msg = "Error occurred while opening a connection to the underlying data source"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while looking up for the certificate carrying the serial number '" + + serialNumber + "' in the underlying certificate repository"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } - public PaginationResult getAllCertificates(PaginationRequest request) - throws CertificateManagementDAOException { + public PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); return certificateDAO.getAllCertificates(request); } catch (SQLException e) { - String errorMsg = "Error when opening connection"; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); + String msg = "Error occurred while opening a connection to the underlying data source"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while looking up for the list of certificates managed in the underlying " + + "certificate repository"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } @Override - public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException { + public boolean removeCertificate(String serialNumber) throws CertificateManagementException { try { CertificateManagementDAOFactory.beginTransaction(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); @@ -175,38 +184,53 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe CertificateManagementDAOFactory.commitTransaction(); return status; } catch (TransactionManagementException e) { - String errorMsg = "Error when deleting"; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOFactory.closeConnection(); + String msg = "Error occurred while removing certificate carrying serial number '" + serialNumber + "'"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (CertificateManagementDAOException e) { + CertificateManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while removing the certificate carrying serial number '" + serialNumber + + "' from the certificate repository"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); } } @Override - public List getCertificates() throws CertificateManagementDAOException { + public List getCertificates() throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); return certificateDAO.getAllCertificates(); } catch (SQLException e) { - String errorMsg = "Error when opening connection"; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); + String msg = "Error occurred while opening a connection to the underlying data source"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while looking up for the list of certificates managed in the " + + "underlying certificate repository"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } - @Override public List searchCertificates(String serialNumber) throws CertificateManagementDAOException { + @Override + public List searchCertificates(String serialNumber) throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); return certificateDAO.searchCertificate(serialNumber); } catch (SQLException e) { - String errorMsg = "Error when opening connection"; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); + String msg = "Error occurred while opening a connection to the underlying data source"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while searching for the list of certificates carrying the serial number '" + + serialNumber + "' in the underlying certificate repository"; + log.error(msg, e); + throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index d60e60d0972..d7dd0e5a70d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -121,8 +121,8 @@ public class OperationManagerImpl implements OperationManager { notificationStrategy.execute(new NotificationContext(deviceId, operation)); } catch (PushNotificationExecutionFailedException e) { log.error("Error occurred while sending push notifications to " + - deviceId.getType() + " device carrying id '" + - deviceId + "'", e); + deviceId.getType() + " device carrying id '" + + deviceId + "'", e); } } } @@ -188,7 +188,7 @@ public class OperationManagerImpl implements OperationManager { return deviceDAO.getDevice(deviceId, tenantId); } catch (SQLException e) { throw new OperationManagementException("Error occurred while opening a connection the data " + - "source", e); + "source", e); } catch (DeviceManagementDAOException e) { OperationManagementDAOFactory.rollbackTransaction(); throw new OperationManagementException( @@ -209,44 +209,49 @@ public class OperationManagerImpl implements OperationManager { throw new UnauthorizedDeviceAccessException("User '" + getUser() + "' is not authorized to " + "fetch operations on device '" + deviceId.getId() + "'"); } - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - if (enrolmentId < 0) { - return null; - } - OperationManagementDAOFactory.openConnection(); - List operationList = - operationDAO.getOperationsForDevice(enrolmentId); - - operations = new ArrayList<>(); - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { - Operation operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); - } - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving metadata of '" + - deviceId.getType() + "' device carrying the identifier '" + - deviceId.getId() + "'"); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + this.getUser(), e); } + + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving metadata of '" + + deviceId.getType() + "' device carrying the identifier '" + + deviceId.getId() + "'"); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + if (enrolmentId < 0) { + return null; + } + OperationManagementDAOFactory.openConnection(); + List operationList = + operationDAO.getOperationsForDevice(enrolmentId); + + operations = new ArrayList<>(); + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { + Operation operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } return operations; } @@ -259,55 +264,59 @@ public class OperationManagerImpl implements OperationManager { try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.openConnection(); - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for given device " + - "Identifier:" + deviceId.getId() + " and given type" + - deviceId.getType()); - } - List operationList = - operationDAO.getOperationsForDevice(enrolmentId, request); - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { - Operation operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); - } - paginationResult = new PaginationResult(); - int count = operationDAO.getOperationCountForDevice(enrolmentId); - paginationResult.setData(operations); - paginationResult.setRecordsTotal(count); - paginationResult.setRecordsFiltered(count); - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving metadata of '" + - deviceId.getType() + "' device carrying the identifier '" + - deviceId.getId() + "'"); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - } else { - log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); + if (!isUserAuthorized) { + log.error("User : " + getUser() + " is not authorized to fetch operations on device : " + + deviceId.getId()); } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + this.getUser(), e); } + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving metadata of '" + + deviceId.getType() + "' device carrying the identifier '" + + deviceId.getId() + "'"); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device " + + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); + } + List operationList = + operationDAO.getOperationsForDevice(enrolmentId, request); + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { + Operation operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + paginationResult = new PaginationResult(); + int count = operationDAO.getOperationCountForDevice(enrolmentId); + paginationResult.setData(operations); + paginationResult.setRecordsTotal(count); + paginationResult.setRecordsFiltered(count); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + return paginationResult; } @@ -323,57 +332,61 @@ public class OperationManagerImpl implements OperationManager { try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - OperationManagementDAOFactory.openConnection(); - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for the given device Identifier:" + - deviceId.getId() + " and given type:" + - deviceId.getType()); - } - dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - Operation operation; - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { - operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); - } - Collections.sort(operations, new OperationCreateTimeComparator()); - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "pending operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + - "' and device Id '" + deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - } else { - log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + if (!isUserAuthorized) { + log.error("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + this.getUser(), e); } + + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId() + "'", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for the given device Identifier:" + + deviceId.getId() + " and given type:" + + deviceId.getType()); + } + dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + Operation operation; + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { + operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + Collections.sort(operations, new OperationCreateTimeComparator()); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "pending operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } return operations; } @@ -387,63 +400,67 @@ public class OperationManagerImpl implements OperationManager { try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - OperationManagementDAOFactory.openConnection(); - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for given device " + - "Identifier:" + deviceId.getId() + " and given type" + - deviceId.getType()); - } - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. - getNextOperation(enrolmentId); - if (dtoOperation != null) { - if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND. - equals(dtoOperation.getType())) { - org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG. - equals(dtoOperation.getType())) { - dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE. - equals(dtoOperation.getType())) { - dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY. - equals(dtoOperation.getType())) { - dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); - } - operation = OperationDAOUtil.convertOperation(dtoOperation); - } - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving next pending operation", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + - "' and device Id '" + deviceId.getId(), e); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - } else { - log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + if (!isUserAuthorized) { + log.error("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + this.getUser(), e); } + + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId(), e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device " + + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); + } + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. + getNextOperation(enrolmentId); + if (dtoOperation != null) { + if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND. + equals(dtoOperation.getType())) { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; + commandOperation = + (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. + getOperation(dtoOperation.getId()); + dtoOperation.setEnabled(commandOperation.isEnabled()); + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG. + equals(dtoOperation.getType())) { + dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE. + equals(dtoOperation.getType())) { + dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY. + equals(dtoOperation.getType())) { + dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + } + operation = OperationDAOUtil.convertOperation(dtoOperation); + } + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving next pending operation", e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } return operation; } @@ -457,52 +474,53 @@ public class OperationManagerImpl implements OperationManager { try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection to the" + - " data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - OperationManagementDAOFactory.beginTransaction(); - boolean isUpdated = false; - if (operation.getStatus() != null) { - isUpdated = operationDAO.updateOperationStatus(enrolmentId, operationId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status. - valueOf(operation.getStatus().toString())); - } - if (isUpdated && operation.getOperationResponse() != null) { - operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); - } - OperationManagementDAOFactory.commitTransaction(); - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException( - "Error occurred while updating the operation: " + operationId + " status:" + - operation.getStatus(), e); - } catch (DeviceManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException( - "Error occurred while fetching the device for device identifier: " + deviceId.getId() + - "type:" + deviceId.getType(), e); - } catch (TransactionManagementException e) { - throw new OperationManagementException("Error occurred while initiating a transaction", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - } else { - log.info("User : " + getUser() + " is not authorized to update operations on device : " + if (!isUserAuthorized) { + log.error("User : " + getUser() + " is not authorized to update operations on device : " + deviceId.getId()); } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + this.getUser(), e); } + + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening a connection to the" + + " data source", e); + } catch (DeviceManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException( + "Error occurred while fetching the device for device identifier: " + deviceId.getId() + + "type:" + deviceId.getType(), e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + OperationManagementDAOFactory.beginTransaction(); + boolean isUpdated = false; + if (operation.getStatus() != null) { + isUpdated = operationDAO.updateOperationStatus(enrolmentId, operationId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status. + valueOf(operation.getStatus().toString())); + } + if (isUpdated && operation.getOperationResponse() != null) { + operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); + } + OperationManagementDAOFactory.commitTransaction(); + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException( + "Error occurred while updating the operation: " + operationId + " status:" + + operation.getStatus(), e); + } catch (TransactionManagementException e) { + throw new OperationManagementException("Error occurred while initiating a transaction", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } } @Override @@ -538,68 +556,72 @@ public class OperationManagerImpl implements OperationManager { try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.openConnection(); - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for given device identifier: " + - deviceId.getId() + " type: " + deviceId.getType()); - } - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. - getOperationByDeviceAndId(enrolmentId, operationId); - if (dtoOperation.getType(). - equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { - org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (dtoOperation.getType(). - equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { - dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals( - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) { - dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals( - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) { - dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); - } - - if (dtoOperation == null) { - throw new OperationManagementException("Operation not found for operation Id:" + operationId + - " device id:" + deviceId.getId()); - } - operation = OperationDAOUtil.convertOperation(dtoOperation); - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + - "' and device Id '" + deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening connection to the data source", - e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - } else { - log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + if (!isUserAuthorized) { + log.error("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + this.getUser(), e); } + + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening connection to the data source", + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device identifier: " + + deviceId.getId() + " type: " + deviceId.getType()); + } + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. + getOperationByDeviceAndId(enrolmentId, operationId); + if (dtoOperation.getType(). + equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; + commandOperation = + (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. + getOperation(dtoOperation.getId()); + dtoOperation.setEnabled(commandOperation.isEnabled()); + } else if (dtoOperation.getType(). + equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { + dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); + } else if (dtoOperation.getType().equals( + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) { + dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); + } else if (dtoOperation.getType().equals( + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) { + dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + } + + if (dtoOperation == null) { + throw new OperationManagementException("Operation not found for operation Id:" + operationId + + " device id:" + deviceId.getId()); + } + operation = OperationDAOUtil.convertOperation(dtoOperation); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening connection to the data source", + e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + return operation; } @@ -612,56 +634,7 @@ public class OperationManagerImpl implements OperationManager { try { boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - if (isUserAuthorized) { - try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - OperationManagementDAOFactory.openConnection(); - - if (enrolmentId < 0) { - throw new OperationManagementException( - "Device not found for device id:" + deviceId.getId() + " " + "type:" + - deviceId.getType()); - } - - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus = - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString()); - dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus)); - dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - Operation operation; - - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { - operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); - } - - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + - deviceId.getId() + "' and status:" + status.toString(), e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + - "' and device Id '" + deviceId.getId(), e); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - } else { + if (!isUserAuthorized) { log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); } @@ -669,6 +642,59 @@ public class OperationManagerImpl implements OperationManager { throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + this.getUser(), e); } + + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId(), e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + try { + OperationManagementDAOFactory.openConnection(); + + if (enrolmentId < 0) { + throw new OperationManagementException( + "Device not found for device id:" + deviceId.getId() + " " + "type:" + + deviceId.getType()); + } + + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus = + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString()); + dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus)); + dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + + Operation operation; + + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { + operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + + deviceId.getId() + "' and status:" + status.toString(), e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } return operations; } @@ -809,7 +835,8 @@ public class OperationManagerImpl implements OperationManager { } @Override - public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException { + public List getActivitiesUpdatedAfter(long timestamp, int limit, + int offset) throws OperationManagementException { try { OperationManagementDAOFactory.openConnection(); return operationDAO.getActivitiesUpdatedAfter(timestamp, limit, offset); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java index 8cc205f210c..58c6f621ac8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.core.search.util; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; From ea032337d3e158aaa47505cc9e6f743c44e12bb2 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 26 Jul 2016 11:30:28 +0530 Subject: [PATCH 14/15] Changing Kernel version that carbon-device-mgt repository depends on and fixing the axiom version range --- .../pom.xml | 14 +++++++------- pom.xml | 16 ++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml index 50e79984474..daddc132a19 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml @@ -49,10 +49,10 @@ org.wso2.carbon.device.mgt.api.feature zip - - org.wso2.carbon.commons - org.wso2.carbon.email.verification - + + + + @@ -114,9 +114,9 @@ org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.common:${carbon.device.mgt.version} - - org.wso2.carbon.commons:org.wso2.carbon.email.verification - + + + org.wso2.carbon.identity:org.wso2.carbon.identity.oauth.stub:${carbon.identity.version} diff --git a/pom.xml b/pom.xml index bc5f7311a22..d9afb815108 100644 --- a/pom.xml +++ b/pom.xml @@ -757,11 +757,11 @@ ${axiom.wso2.version} - - org.wso2.carbon.commons - org.wso2.carbon.email.verification - ${carbon.commons.version} - + + + + + @@ -1739,7 +1739,7 @@ 6.1.1 - 4.4.3 + 4.4.7 [4.4.0, 5.0.0) 1.5.4 1.3 @@ -1791,8 +1791,8 @@ 4.5.8 - 1.2.11-wso2v5 - [1.2.11.wso2v5, 1.3.0) + 1.2.11-wso2v11 + [1.2.11, 1.3.0) 1.2.11.wso2v5 From c228f03481d5094599851d814da4e66bdf4b5ae6 Mon Sep 17 00:00:00 2001 From: dilanua Date: Tue, 26 Jul 2016 11:34:52 +0530 Subject: [PATCH 15/15] Refactoring oauth token handling functions and dependants --- .../devicemgt/app/modules/backend-service-invoker.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/login.js | 9 +++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js index 1e374b434d3..e93fe88aaac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js @@ -41,7 +41,7 @@ var backendServiceInvoker = function () { * If the token pair s not set in the session this will send a redirect to the login page. */ privateMethods.getAccessToken = function () { - var tokenPair = session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]); + var tokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"])); if (tokenPair) { return tokenPair.accessToken; } else { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 038082c50c7..eeeb81ba5ef 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -23,20 +23,17 @@ var onFail; var log = new Log("/app/modules/login.js"); var constants = require("/app/modules/constants.js"); onSuccess = function (context) { - var properties; var utility = require("/app/modules/utility.js").utility; var apiWrapperUtil = require("/app/modules/api-wrapper-util.js").apiWrapperUtil; if (context.input.samlToken) { - properties = {samlToken: context.input.samlToken}; - apiWrapperUtil.setupAccessTokenPair(constants.GRANT_TYPE_SAML, properties); + apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken); } else { - properties = {username: context.input.username, password: context.input.password}; - apiWrapperUtil.setupAccessTokenPair(constants.GRANT_TYPE_PASSWORD, properties); + apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(context.input.username, context.input.password); } var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var carbonServer = require("carbon").server; (new carbonServer.Server({url: devicemgtProps["adminService"]})) - .login(context.input.username, context.input.password); + .login(context.input.username, context.input.password); }; onFail = function (error) {