From a51e7646e39b5ee3e1bad1d99d3344d275733e3d Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 26 Aug 2015 12:48:53 +0530 Subject: [PATCH 01/25] Fixing issues of previous PRs --- .../carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 7456d57a8c..f026f789d0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -746,12 +746,9 @@ public class PolicyManagerImpl implements PolicyManager { @Override public int getPolicyCount() throws PolicyManagementException { - - int policyCount; try { PolicyManagementDAOFactory.openConnection(); - policyCount = policyDAO.getPolicyCount(); - return policyCount; + return policyDAO.getPolicyCount(); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting policy count", e); } catch (SQLException e) { From 5e285071d801761bdd15cec554a1c3f112d5eb99 Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 26 Aug 2015 15:16:29 +0530 Subject: [PATCH 02/25] Removed unnecessary white spaces --- .../identity/oauth/extension/profile/RegistrationProfile.java | 2 -- .../carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java index 2c1a42bae3..25a760ab25 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java @@ -164,6 +164,4 @@ public class RegistrationProfile { public void setGrantType(String grantType) { this.grantType = grantType; } - - } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java index fde4b6d173..e10e1e3097 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java @@ -102,7 +102,7 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { if (pipDevice.getRoles() != null) { policies = policyFilter.filterRolesBasedPolicies(pipDevice.getRoles(), policies); } - if(pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { + if (pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies); } From 97c19c23b0cf275d0a6d26ced3e1d5a59607af37 Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 26 Aug 2015 17:14:12 +0530 Subject: [PATCH 03/25] Added method level comments and null checks in DCA --- .../extension/DynamicClientRegistrationUtil.java | 5 +++++ .../oauth/extension/RegistrationService.java | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java index 0cdb0a097f..0a7698217a 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java @@ -228,6 +228,11 @@ public class DynamicClientRegistrationUtil { oAuthAdminService.removeOAuthApplicationData(consumerKey); ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + + if (appMgtService == null) { + throw new APIManagementException("Error occurred while retrieving Application Management" + + "Service"); + } ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); if (createdServiceProvider == null) { diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java index a31673a776..962b721091 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java @@ -45,9 +45,24 @@ public interface RegistrationService { } } + /** + * This method is used to register an Oauth application. + * + * @param profile contains the necessary attributes that are + * needed in order to register an app. + * @return Status 200 if success including consumerKey and consumerSecret. + */ @POST Response register(RegistrationProfile profile); + /** + * This method is used to remove already registered Oauth application. + * + * @param applicationName name of the application. + * @param userId name of the application owner. + * @param consumerKey provided consumerKey for the registered application. + * @return Status 200 if success. + */ @DELETE public Response unregister(@QueryParam("applicationName") String applicationName, @QueryParam("userId") String userId, From 8c748b3dfded1339ca727dc4395a31423f6c914a Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 26 Aug 2015 17:45:21 +0530 Subject: [PATCH 04/25] Removed unnecessary comments --- .../DeviceManagementProviderService.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 21 ++++++-------- .../pom.xml | 28 ------------------- 3 files changed, 9 insertions(+), 42 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 4aaf8bf06f..bd0223e962 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -93,7 +93,7 @@ public interface DeviceManagementProviderService extends OperationManager { void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException; /** - * This method is used to retrieve list of devices based on the device status + * This method is used to retrieve list of devices based on the device status. * * @param status Device status * @return List of devices diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 197a9321e3..3e05baf788 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -492,8 +492,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { Device device; try { + DeviceManagementDAOFactory.openConnection(); device = deviceDAO.getDevice(deviceId, this.getTenantId()); - } catch (DeviceManagementDAOException e) { + } catch (DeviceManagementDAOException | SQLException e) { throw new DeviceManagementException("Error occurred while obtaining the device for id " + "'" + deviceId.getId() + "'", e); } finally { @@ -731,10 +732,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } for (Device device : userDevices) { - Device dmsDevice = - this.getPluginRepository().getDeviceManagementService( - device.getType()).getDeviceManager().getDevice( - new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + Device dmsDevice = this.getDeviceManager(device.getType()). + getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); if (dmsDevice != null) { device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -771,10 +770,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } for (Device device : allDevices) { - Device dmsDevice = - this.getPluginRepository().getDeviceManagementService( - device.getType()).getDeviceManager().getDevice( - new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + Device dmsDevice = this.getDeviceManager(device.getType()). + getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); if (dmsDevice != null) { device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -835,10 +832,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } for (Device device : allDevices) { - Device dmsDevice = - this.getPluginRepository().getDeviceManagementService( - device.getType()).getDeviceManager().getDevice( - new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + Device dmsDevice = this.getDeviceManager(device.getType()). + getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); if (dmsDevice != null) { device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); diff --git a/features/oauth-extensions/org.wso2.carbon.oauth.extensions.server.feature/pom.xml b/features/oauth-extensions/org.wso2.carbon.oauth.extensions.server.feature/pom.xml index a20ebb17c6..eae36b42e9 100644 --- a/features/oauth-extensions/org.wso2.carbon.oauth.extensions.server.feature/pom.xml +++ b/features/oauth-extensions/org.wso2.carbon.oauth.extensions.server.feature/pom.xml @@ -37,14 +37,6 @@ This feature contains oauth functionality - - - - - - - - @@ -101,8 +93,6 @@ - - org.wso2.maven carbon-p2-plugin @@ -123,20 +113,6 @@ org.eclipse.equinox.p2.type.group:false - - - - - - - - - - - - - - org.wso2.carbon.core.server:${carbon.kernel.version} @@ -145,10 +121,6 @@ - - - - From 7fed00a14db8dd7ab5324badddb45827c175392f Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 26 Aug 2015 18:10:10 +0530 Subject: [PATCH 05/25] Removed unnecessary logs and added null checks in MonitoringManager --- .../mgt/core/mgt/impl/MonitoringManagerImpl.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 34a9ad9aaa..b4445af160 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -293,13 +293,16 @@ public class MonitoringManagerImpl implements MonitoringManager { } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Error occurred reading the applied policies to devices.", e); + } catch (DeviceManagementException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyComplianceException("Error occurred while adding monitoring operation to DB."); } finally { PolicyManagementDAOFactory.closeConnection(); } } private void addMonitoringOperationsToDatabase(List devices) - throws PolicyComplianceException, OperationManagementException { + throws PolicyComplianceException, OperationManagementException, DeviceManagementException { List deviceIdentifiers = this.getDeviceIdentifiersFromDevices(devices); CommandOperation monitoringOperation = new CommandOperation(); @@ -308,9 +311,10 @@ public class MonitoringManagerImpl implements MonitoringManager { monitoringOperation.setCode(OPERATION_MONITOR); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + if (service == null) { + throw new DeviceManagementException("Error occurred while retrieving Device Management Service"); + } service.addOperation(monitoringOperation, deviceIdentifiers); -// PolicyManagementDataHolder.getInstance().getDeviceManagementService(). -// addOperation(monitoringOperation, deviceIdentifiers); } private List getDeviceIdentifiersFromDevices(List devices) { From 94326323bcf53296d97517f6bf91d33eed695022 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 27 Aug 2015 01:00:59 +0530 Subject: [PATCH 06/25] Added class level and method level comments for Policy core --- .../policy/mgt/core/dao/FeatureDAO.java | 84 +++++++++-- .../policy/mgt/core/dao/ProfileDAO.java | 49 ++++++- .../mgt/core/dao/impl/FeatureDAOImpl.java | 134 ++---------------- .../mgt/core/dao/impl/ProfileDAOImpl.java | 20 ++- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 4 +- .../mgt/core/mgt/impl/ProfileManagerImpl.java | 2 +- 6 files changed, 148 insertions(+), 145 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java index 19c9c13715..3b8ecec20c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java @@ -25,34 +25,102 @@ import org.wso2.carbon.policy.mgt.common.ProfileFeature; import java.util.List; +/** + * This interface represents the key operations related to profile features of device policies. + */ public interface FeatureDAO { -/* Feature addFeature(Feature feature) throws FeatureManagerDAOException; - - List addFeatures(List feature) throws FeatureManagerDAOException; - - Feature updateFeature(Feature feature) throws FeatureManagerDAOException;*/ - + /** + * This method is used to add a feature related to given profile. + * + * @param feature consists of device specific configurations. + * @param profileId id of the profile. + * @return returns ProfileFeature object. + * @throws FeatureManagerDAOException + */ ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException; + /** + * This method is used to update a feature related to given profile. + * @param feature consists of device specific configurations. + * @param profileId id of the profile. + * @return returns updated ProfileFeature object. + * @throws FeatureManagerDAOException + */ ProfileFeature updateProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException; + /** + * This method is used to add set of features to a given profile. + * + * @param features consists of device specific configurations. + * @param profileId id of the profile. + * @return returns list of ProfileFeature objects. + * @throws FeatureManagerDAOException + */ List addProfileFeatures(List features, int profileId) throws FeatureManagerDAOException; + /** + * This method is used to update set of features to a given profile. + * + * @param features consists of device specific configurations. + * @param profileId id of the profile. + * @return returns list of ProfileFeature objects. + * @throws FeatureManagerDAOException + */ List updateProfileFeatures(List features, int profileId) throws FeatureManagerDAOException; + /** + * This method is used to retrieve all the profile features. + * + * @return returns list of ProfileFeature objects. + * @throws FeatureManagerDAOException + */ List getAllProfileFeatures() throws FeatureManagerDAOException; + /** + * This method is used to retrieve all the profile features based on device type. + * + * @return returns list of ProfileFeature objects. + * @throws FeatureManagerDAOException + */ List getAllFeatures(String deviceType) throws FeatureManagerDAOException; - List getFeaturesForProfile(int ProfileId) throws FeatureManagerDAOException; - + /** + * This method is used to retrieve all the profile features of given profile. + * + * @param profileId id of the profile. + * @return returns list of ProfileFeature objects. + * @throws FeatureManagerDAOException + */ + List getFeaturesForProfile(int profileId) throws FeatureManagerDAOException; + + /** + * This method is used remove a feature. + * + * @param featureId id of the removing feature. + * @return returns true if success. + * @throws FeatureManagerDAOException + */ boolean deleteFeature(int featureId) throws FeatureManagerDAOException; + /** + * This method is used to remove set of features of given profile. + * + * @param profile that contains features to be removed. + * @return returns true if success. + * @throws FeatureManagerDAOException + */ boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagerDAOException; + /** + * This method is used to remove set of features of given profile id. + * + * @param profileId id of the profile. + * @return returns true if success. + * @throws FeatureManagerDAOException + */ boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/ProfileDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/ProfileDAO.java index 174ca08c48..5d91650d7e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/ProfileDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/ProfileDAO.java @@ -24,20 +24,67 @@ import org.wso2.carbon.policy.mgt.common.Profile; import java.util.List; +/** + * This interface represents the key operations related to policy profile. + */ public interface ProfileDAO { + /** + * This method is used to add a profile. + * + * @param profile profile object. + * @return returns added profile object. + * @throws ProfileManagerDAOException + */ Profile addProfile(Profile profile) throws ProfileManagerDAOException; + /** + * This method is used to update a profile + * @param profile profile object. + * @return returns updated profile object. + * @throws ProfileManagerDAOException + */ Profile updateProfile(Profile profile) throws ProfileManagerDAOException; + /** + * This method is used to remove a profile. + * @param profile profile object + * @return returns true if success. + * @throws ProfileManagerDAOException + */ boolean deleteProfile(Profile profile) throws ProfileManagerDAOException; + /** + * This method is used to remove a profile of given policy id. + * @param policyId policy id. + * @return returns true if success. + * @throws ProfileManagerDAOException + */ boolean deleteProfile(int policyId) throws ProfileManagerDAOException; - Profile getProfiles(int profileId) throws ProfileManagerDAOException; + /** + * This method is used to retrieve a profile when id is given. + * @param profileId profile id. + * @return returns profile object. + * @throws ProfileManagerDAOException + */ + Profile getProfile(int profileId) throws ProfileManagerDAOException; + /** + * This method is used to retrieve all the profiles. + * + * @return returns a list of profile objects. + * @throws ProfileManagerDAOException + */ List getAllProfiles() throws ProfileManagerDAOException; + /** + * This method is used to retrieve all the profile of given device type. + * + * @param deviceType device type object. + * @return retruns list of profiles. + * @throws ProfileManagerDAOException + */ List getProfilesOfDeviceType(DeviceType deviceType) throws ProfileManagerDAOException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/FeatureDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/FeatureDAOImpl.java index 37dde34099..8670c35b7f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/FeatureDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/FeatureDAOImpl.java @@ -43,115 +43,6 @@ public class FeatureDAOImpl implements FeatureDAO { private static final Log log = LogFactory.getLog(FeatureDAOImpl.class); - -/* @Override - public Feature addFeature(Feature feature) throws FeatureManagerDAOException { - - Connection conn; - PreparedStatement stmt = null; - ResultSet generatedKeys = null; - - try { - conn = this.getConnection(); - String query = "INSERT INTO DM_FEATURES (NAME, CODE, DESCRIPTION) VALUES (?, ?, ?)"; - stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); - stmt.setString(1, feature.getName()); - stmt.setString(2, feature.getCode()); - stmt.setString(3, feature.getDescription()); - int affectedRows = stmt.executeUpdate(); - - if (log.isDebugEnabled()) { - log.debug(affectedRows + " feature is added."); - } - generatedKeys = stmt.getGeneratedKeys(); - - while (generatedKeys.next()) { - feature.setId(generatedKeys.getInt(1)); - } - - } catch (SQLException e) { - String msg = "Error occurred while adding feature to the database."; - log.error(msg, e); - throw new FeatureManagerDAOException(msg, e); - } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); - } - return feature; - }*/ - - /* @Override - public List addFeatures(List features) throws FeatureManagerDAOException { - - Connection conn; - PreparedStatement stmt = null; - ResultSet generatedKeys = null; - List featureList = new ArrayList(); - - try { - conn = this.getConnection(); - String query = "INSERT INTO DM_FEATURES (NAME, CODE, DESCRIPTION) VALUES (?, ?, ?)"; - stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); - - for (Feature feature : features) { - stmt.setString(1, feature.getName()); - stmt.setString(2, feature.getCode()); - stmt.setString(3, feature.getDescription()); - stmt.addBatch(); - } - - int[] affectedRows = stmt.executeBatch(); - - generatedKeys = stmt.getGeneratedKeys(); - - if (log.isDebugEnabled()) { - log.debug(affectedRows.length + " features are added to the database."); - } - generatedKeys = stmt.getGeneratedKeys(); - int i = 0; - - while (generatedKeys.next()) { - features.get(i).setId(generatedKeys.getInt(1)); - i++; - } - } catch (SQLException e) { - String msg = "Error occurred while adding feature to the database."; - log.error(msg, e); - throw new FeatureManagerDAOException(msg, e); - } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); - } - return featureList; - }*/ - - - /* @Override - public Feature updateFeature(Feature feature) throws FeatureManagerDAOException { - - Connection conn; - PreparedStatement stmt = null; - - try { - conn = this.getConnection(); - String query = "UPDATE DM_FEATURES SET NAME = ?, CODE = ?, DESCRIPTION = ? WHERE ID = ?"; - stmt = conn.prepareStatement(query); - stmt.setString(1, feature.getName()); - stmt.setString(2, feature.getCode()); - stmt.setString(3, feature.getDescription()); - stmt.setInt(4, feature.getId()); - stmt.executeUpdate(); - - } catch (SQLException e) { - String msg = "Error occurred while updating feature " + feature.getName() + " (Feature Name) to the - database."; - log.error(msg, e); - throw new FeatureManagerDAOException(msg, e); - } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, null); - } - - return feature; - }*/ - @Override public ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException { return null; @@ -247,7 +138,6 @@ public class FeatureDAOImpl implements FeatureDAO { @Override public boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagerDAOException { - Connection conn; PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -258,9 +148,10 @@ public class FeatureDAOImpl implements FeatureDAO { stmt = conn.prepareStatement(query); stmt.setInt(1, profile.getProfileId()); stmt.setInt(2, tenantId); - stmt.executeUpdate(); - return true; - + if (stmt.executeUpdate() > 0) { + return true; + } + return false; } catch (SQLException e) { throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e); } finally { @@ -270,7 +161,6 @@ public class FeatureDAOImpl implements FeatureDAO { @Override public boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException { - Connection conn; PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -280,9 +170,10 @@ public class FeatureDAOImpl implements FeatureDAO { stmt = conn.prepareStatement(query); stmt.setInt(1, profileId); stmt.setInt(2, tenantId); - stmt.executeUpdate(); - return true; - + if (stmt.executeUpdate() > 0) { + return true; + } + return false; } catch (SQLException e) { throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e); } finally { @@ -448,7 +339,6 @@ public class FeatureDAOImpl implements FeatureDAO { @Override public boolean deleteFeature(int featureId) throws FeatureManagerDAOException { - Connection conn; PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -459,9 +349,10 @@ public class FeatureDAOImpl implements FeatureDAO { stmt = conn.prepareStatement(query); stmt.setInt(1, featureId); stmt.setInt(2, tenantId); - stmt.executeUpdate(); - return true; - + if(stmt.executeUpdate() > 0) { + return true; + } + return false; } catch (SQLException e) { throw new FeatureManagerDAOException("Unable to delete the feature " + featureId + " (Feature ID) " + "from database.", e); @@ -471,7 +362,6 @@ public class FeatureDAOImpl implements FeatureDAO { } private Connection getConnection() throws FeatureManagerDAOException { - try { return PolicyManagementDAOFactory.getConnection(); } catch (PolicyManagerDAOException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java index 58ceefba76..89d06d0a10 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java @@ -133,7 +133,6 @@ public class ProfileDAOImpl implements ProfileDAO { @Override public boolean deleteProfile(Profile profile) throws ProfileManagerDAOException { - Connection conn; PreparedStatement stmt = null; @@ -142,9 +141,10 @@ public class ProfileDAOImpl implements ProfileDAO { String query = "DELETE FROM DM_PROFILE WHERE ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, profile.getProfileId()); - stmt.executeUpdate(); - return true; - + if (stmt.executeUpdate() > 0) { + return true; + } + return false; } catch (SQLException e) { String msg = "Error occurred while deleting the profile from the data base."; log.error(msg); @@ -164,9 +164,10 @@ public class ProfileDAOImpl implements ProfileDAO { String query = "DELETE FROM DM_PROFILE WHERE ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, profileId); - stmt.executeUpdate(); - return true; - + if (stmt.executeUpdate() > 0) { + return true; + } + return false; } catch (SQLException e) { String msg = "Error occurred while deleting the profile from the data base."; log.error(msg); @@ -178,8 +179,7 @@ public class ProfileDAOImpl implements ProfileDAO { @Override - public Profile getProfiles(int profileId) throws ProfileManagerDAOException { - + public Profile getProfile(int profileId) throws ProfileManagerDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -217,7 +217,6 @@ public class ProfileDAOImpl implements ProfileDAO { @Override public List getAllProfiles() throws ProfileManagerDAOException { - Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -259,7 +258,6 @@ public class ProfileDAOImpl implements ProfileDAO { @Override public List getProfilesOfDeviceType(DeviceType deviceType) throws ProfileManagerDAOException { - Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index f026f789d0..1d31fd0738 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -397,7 +397,7 @@ public class PolicyManagerImpl implements PolicyManager { // policyDAO.getTimesOfPolicy(policy); // policyDAO.getLocationsOfPolicy(policy); - profile = profileDAO.getProfiles(profileId); + profile = profileDAO.getProfile(profileId); policy.setProfile(profile); policy.setRoles(roleNames); @@ -433,7 +433,7 @@ public class PolicyManagerImpl implements PolicyManager { // policyDAO.getTimesOfPolicy(policy); // policyDAO.getLocationsOfPolicy(policy); - Profile profile = profileDAO.getProfiles(policy.getProfileId()); + Profile profile = profileDAO.getProfile(policy.getProfileId()); policy.setProfile(profile); policy.setRoles(roleNames); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 2dc77739cd..197b0f933b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -147,7 +147,7 @@ public class ProfileManagerImpl implements ProfileManager { try { PolicyManagementDAOFactory.openConnection(); - profile = profileDAO.getProfiles(profileId); + profile = profileDAO.getProfile(profileId); featureList = featureDAO.getFeaturesForProfile(profileId); deviceType = deviceTypeDAO.getDeviceType(profile.getDeviceType().getId()); From 460fda1bb948c29d9b36fa4e6039095c6b37cf2d Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 27 Aug 2015 10:43:52 +0530 Subject: [PATCH 07/25] Removed unnecessary new lines in DeviceDAOImpl --- .../mgt/core/dao/impl/DeviceDAOImpl.java | 112 +++++++++--------- 1 file changed, 53 insertions(+), 59 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java index 6d8d4107bf..df3ee197ba 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java @@ -111,13 +111,12 @@ public class DeviceDAOImpl implements DeviceDAO { Device device = null; try { conn = this.getConnection(); - String sql = - "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT " + - "FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + - "AND TENANT_ID = ?"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + + "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getType()); stmt.setString(2, deviceId.getId()); @@ -144,12 +143,12 @@ public class DeviceDAOImpl implements DeviceDAO { List devices = null; try { conn = this.getConnection(); - String sql = - "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME," + - "d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + + "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, tenantId); @@ -176,12 +175,12 @@ public class DeviceDAOImpl implements DeviceDAO { List devices = null; try { conn = this.getConnection(); - String sql = - "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME " + - "AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + + "d.NAME, d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + + "AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); @@ -207,13 +206,12 @@ public class DeviceDAOImpl implements DeviceDAO { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = - "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT t.NAME AS DEVICE_TYPE, d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e, (SELECT t.NAME AS DEVICE_TYPE, d.ID, d.DESCRIPTION, " + + "d.NAME, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, tenantId); @@ -281,12 +279,12 @@ public class DeviceDAOImpl implements DeviceDAO { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = - "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DESCRIPTION, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + - "AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceName + "%"); stmt.setInt(2, tenantId); @@ -314,9 +312,8 @@ public class DeviceDAOImpl implements DeviceDAO { int enrolmentId = -1; try { conn = this.getConnection(); - String sql = - "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, " + - "TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)"; + String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " + + "DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, device.getId()); stmt.setString(2, device.getEnrolmentInfo().getOwner()); @@ -346,10 +343,9 @@ public class DeviceDAOImpl implements DeviceDAO { PreparedStatement stmt = null; try { conn = this.getConnection(); - String sql = - "UPDATE DM_ENROLMENT SET STATUS = ? WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + - "AND OWNER = ? AND TENANT_ID = ?"; + String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? " + + "AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, status.toString()); stmt.setString(2, deviceId.getId()); @@ -375,10 +371,9 @@ public class DeviceDAOImpl implements DeviceDAO { Status status = null; try { conn = this.getConnection(); - String sql = - "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = " + - "(SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND " + - "d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?"; + String sql = "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? " + + "AND t.NAME = ? AND d.TENANT_ID = ?) AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); @@ -407,11 +402,11 @@ public class DeviceDAOImpl implements DeviceDAO { EnrolmentInfo enrolmentInfo = null; try { conn = this.getConnection(); - String sql = - "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, " + - "TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + - "AND OWNER = ? AND TENANT_ID = ?"; + String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + + "AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); @@ -438,10 +433,10 @@ public class DeviceDAOImpl implements DeviceDAO { ResultSet rs = null; try { conn = this.getConnection(); - String sql = - "SELECT ID AS ENROLMENT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? " + - "AND d.TENANT_ID = ?) AND STATUS = ? AND TENANT_ID = ?"; + String sql = "SELECT ID AS ENROLMENT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + + "AND STATUS = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); @@ -490,13 +485,12 @@ public class DeviceDAOImpl implements DeviceDAO { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = - "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE FROM DM_ENROLMENT e WHERE TENANT_ID = ? " + - "AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_ID = e.DEVICE_ID " + - "AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE FROM DM_ENROLMENT e WHERE TENANT_ID = ? " + + "AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_ID = e.DEVICE_ID " + + "AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, status.toString()); From abc16557dcc83724c9f0ce6be1fe4e4b251e27d8 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 27 Aug 2015 10:45:10 +0530 Subject: [PATCH 08/25] Removed unnecessary new lines in DeviceDAOImpl --- .../carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java index df3ee197ba..5244ce4abd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java @@ -42,9 +42,8 @@ public class DeviceDAOImpl implements DeviceDAO { int deviceId = -1; try { conn = this.getConnection(); - String sql = - "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) " + - "VALUES (?, ?, ?, ?, ?)"; + String sql = "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, device.getDescription()); stmt.setString(2, device.getName()); @@ -74,9 +73,8 @@ public class DeviceDAOImpl implements DeviceDAO { int deviceId = -1; try { conn = this.getConnection(); - String sql = - "UPDATE DM_DEVICE SET DESCRIPTION = ?, NAME = ? WHERE DEVICE_IDENTIFICATION = ? AND " + - "DEVICE_TYPE_ID = ? AND TENANT_ID = ?"; + String sql = "UPDATE DM_DEVICE SET DESCRIPTION = ?, NAME = ? WHERE DEVICE_IDENTIFICATION = ? AND " + + "DEVICE_TYPE_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, device.getDescription()); stmt.setString(2, device.getName()); From 69cf3f8939d45cd3101527298de57d691cb2ae28 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 27 Aug 2015 17:15:37 +0530 Subject: [PATCH 09/25] Cleaned code and added comments --- .../device/mgt/common/EnrolmentInfo.java | 17 +-- .../carbon/device/mgt/core/dao/DeviceDAO.java | 124 +++++++++++++++++- .../operation/mgt/OperationManagerImpl.java | 4 +- .../mgt/dao/impl/CommandOperationDAOImpl.java | 8 +- .../DeviceManagementProviderServiceImpl.java | 8 +- 5 files changed, 140 insertions(+), 21 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index 2c599474fc..1054075c34 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -96,19 +96,14 @@ public class EnrolmentInfo { public boolean equals(Object obj) { if (obj instanceof EnrolmentInfo) { EnrolmentInfo tempInfo = (EnrolmentInfo) obj; - if (owner != null && ownership != null - && tempInfo.getOwner() != null && tempInfo.getOwnership() != null) { - - if (owner.equals(tempInfo.getOwner()) && ownership.equals(tempInfo.getOwnership())) { - return true; - } else { - return false; + if (owner != null && ownership != null) { + if (tempInfo.getOwner() != null && tempInfo.getOwnership() != null) { + if (owner.equals(tempInfo.getOwner()) && ownership.equals(tempInfo.getOwnership())) { + return true; + } } - } else { - return false; } - } else { - return false; } + return false; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 5b5d0c66aa..3eb1f48ac4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -31,38 +31,160 @@ import java.util.List; */ public interface DeviceDAO { + /** + * This method is used to add a device. + * + * @param typeId device type id. + * @param device device object. + * @param tenantId tenant id. + * @return returns the id of the persisted device record. + * @throws DeviceManagementDAOException + */ int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to update a given device. + * + * @param typeId device type id. + * @param device device object. + * @param tenantId tenant id. + * @return returns the id of updated device. + * @throws DeviceManagementDAOException + */ int updateDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to remove a device. + * + * @param deviceId id of the device that should be removed. + * @param tenantId tenant id. + * @return returns the id of removed device. + * @throws DeviceManagementDAOException + */ int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve a device of a given id. + * + * @param deviceId device id. + * @param tenantId tenant id. + * @return returns the device object. + * @throws DeviceManagementDAOException + */ Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve all the devices of a given tenant. + * + * @param tenantId tenant id. + * @return returns a list of devices. + * @throws DeviceManagementDAOException + */ List getDevices(int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve all the devices of a given tenant and device type. + * + * @param type device type. + * @param tenantId tenant id. + * @return returns list of devices. + * @throws DeviceManagementDAOException + */ List getDevices(String type, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve devices of a given user. + * @param username user name. + * @param tenantId tenant id. + * @return returns list of devices. + * @throws DeviceManagementDAOException + */ List getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the device count of a given tenant. + * + * @param tenantId tenant id. + * @return returns the device count. + * @throws DeviceManagementDAOException + */ int getDeviceCount(int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve devices of a given device name. + * @param deviceName device name. + * @param tenantId tenant id. + * @return returns list of devices. + * @throws DeviceManagementDAOException + */ List getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to add an enrollment information of a given device. + * + * @param device device object. + * @param tenantId tenant id. + * @return returns the id of the enrollment. + * @throws DeviceManagementDAOException + */ int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to set the current enrollment status of given device and user. + * + * @param deviceId device id. + * @param currentOwner current user name. + * @param status device status. + * @param tenantId tenant id. + * @return returns true if success. + * @throws DeviceManagementDAOException + */ boolean setEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, Status status, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to get the status of current enrollment of a given user and device. + * + * @param deviceId device id. + * @param currentOwner device owner. + * @param tenantId tenant id. + * @return returns current enrollment status. + * @throws DeviceManagementDAOException + */ Status getEnrolmentStatus(DeviceIdentifier deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve current enrollment of a given device and user. + * + * @param deviceId device id. + * @param currentUser user name. + * @param tenantId tenant id. + * @return returns EnrolmentInfo object. + * @throws DeviceManagementDAOException + */ EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; - + /** + * This method is used to retrieve devices of a given enrollment status. + * + * @param status enrollment status. + * @param tenantId tenant id. + * @return returns list of devices. + * @throws DeviceManagementDAOException + */ List getDevicesByStatus(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the enrollment id of a given device and status. + * + * @param deviceId device id. + * @param status enrollment status. + * @param tenantId tenant id. + * @return returns the id of current enrollment. + * @throws DeviceManagementDAOException + */ int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status, int tenantId) throws DeviceManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index b2e593291d..9bdcf595fa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -76,7 +76,7 @@ public class OperationManagerImpl implements OperationManager { log.debug("operation:[" + operation.toString() + "]"); for (DeviceIdentifier deviceIdentifier : deviceIds) { log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" + - deviceIdentifier.getType() + "]"); + deviceIdentifier.getType() + "]"); } } try { @@ -167,7 +167,7 @@ public class OperationManagerImpl implements OperationManager { if (enrolmentId < 0) { throw new OperationManagementException("Device not found for the given device Identifier:" + - deviceId.getId() + " and given type:" + deviceId.getType()); + deviceId.getId() + " and given type:" + deviceId.getType()); } dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java index fa3348789f..f485408d67 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java @@ -120,9 +120,11 @@ public class CommandOperationDAOImpl extends OperationDAOImpl { List commandOperations = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, co1.ENABLED, co1.STATUS, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE FROM (SELECT co.OPERATION_ID, co.ENABLED, dm.STATUS FROM DM_COMMAND_OPERATION co " + - "INNER JOIN (SELECT ENROLMENT_ID, OPERATION_ID, STATUS FROM DM_ENROLMENT_OPERATION_MAPPING WHERE ENROLMENT_ID = ? " + - "AND STATUS = ?) dm ON dm.OPERATION_ID = co.OPERATION_ID) co1 INNER JOIN DM_OPERATION o ON co1.OPERATION_ID = o.ID"; + String sql = "SELECT o.ID, co1.ENABLED, co1.STATUS, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE FROM (SELECT co.OPERATION_ID, co.ENABLED, dm.STATUS " + + "FROM DM_COMMAND_OPERATION co INNER JOIN (SELECT ENROLMENT_ID, OPERATION_ID, STATUS " + + "FROM DM_ENROLMENT_OPERATION_MAPPING WHERE ENROLMENT_ID = ? AND STATUS = ?) dm " + + "ON dm.OPERATION_ID = co.OPERATION_ID) co1 INNER JOIN DM_OPERATION o ON co1.OPERATION_ID = o.ID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 3e05baf788..c44bf6bd27 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -402,7 +402,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); messageBody = messageBody.trim() + System.getProperty("line.separator") + System.getProperty("line.separator") + url.replaceAll("\\{" - + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}", + + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}", URLDecoder.decode(emailMessageProperties.getEnrolmentUrl(), EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); @@ -458,8 +458,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); messageBody = messageBody.trim().replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants - .USERNAME - + "\\}", + .USERNAME + + "\\}", URLEncoder.encode(emailMessageProperties.getUserName(), EmailConstants.EnrolmentEmailConstants .ENCODED_SCHEME)); @@ -468,7 +468,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv .ENCODED_SCHEME)); messageBody = messageBody + System.getProperty("line.separator") + url.replaceAll("\\{" - + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}", + + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}", URLDecoder.decode(emailMessageProperties.getEnrolmentUrl(), EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); From 6385c130122b5a8c042a533aaa586b9408e69e27 Mon Sep 17 00:00:00 2001 From: mharindu Date: Tue, 1 Sep 2015 15:25:16 +0530 Subject: [PATCH 10/25] Fixed issues in DeviceDAO --- .../wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java index f2e68732d4..fc6d79b133 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java @@ -176,9 +176,9 @@ public class DeviceDAOImpl implements DeviceDAO { String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); From 0140974487b85e51f865b33e98c9cf62a9568e5d Mon Sep 17 00:00:00 2001 From: Dilshan Edirisuriya Date: Wed, 2 Sep 2015 10:39:51 +0530 Subject: [PATCH 11/25] Certificate verification --- .../pom.xml | 1 - .../mgt/core/impl/CertificateGenerator.java | 48 +++++++++++++++++++ .../mgt/core/impl/KeyStoreReader.java | 19 ++++++++ .../service/CertificateManagementService.java | 17 ++++--- .../CertificateManagementServiceImpl.java | 8 ++++ 5 files changed, 85 insertions(+), 8 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml index 72647601ae..81d6be9ba4 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml @@ -27,7 +27,6 @@ 4.0.0 - org.wso2.carbon.devicemgt org.wso2.carbon.certificate.mgt.core 0.9.2-SNAPSHOT bundle 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 a1ddb3c20e..e0c999ad07 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 @@ -77,6 +77,7 @@ import java.security.PrivateKey; import java.security.SecureRandom; import java.security.Security; import java.security.SignatureException; +import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; @@ -283,6 +284,53 @@ public class CertificateGenerator { } } + public boolean verifySignature(String headerSignature) throws KeystoreException { + + if (headerSignature == null || headerSignature.isEmpty()) { + return false; + } + + try { + KeyStoreReader keyStoreReader = new KeyStoreReader(); + CMSSignedData signedData = new CMSSignedData(Base64.decodeBase64(headerSignature.getBytes())); + Store reqStore = signedData.getCertificates(); + @SuppressWarnings("unchecked") + Collection reqCerts = reqStore.getMatches(null); + + if (reqCerts != null && reqCerts.size() > 0) { + CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509); + X509CertificateHolder holder = reqCerts.iterator().next(); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded()); + X509Certificate reqCert = (X509Certificate) certificateFactory. + generateCertificate(byteArrayInputStream); + + if(reqCert != null && reqCert.getSerialNumber() != null) { + Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias( + reqCert.getSerialNumber().toString()); + + if (lookUpCertificate != null) { + return true; + } + } + + } + } catch (CMSException e) { + String errorMsg = "CMSException when decoding certificate signature"; + log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } catch (IOException e) { + String errorMsg = "IOException when decoding certificate signature"; + log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } catch (CertificateException e) { + String errorMsg = "CertificateException when decoding certificate signature"; + log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } + + return false; + } + public X509Certificate generateCertificateFromCSR(PrivateKey privateKey, PKCS10CertificationRequest request, String issueSubject) 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 f714a4746b..1b82bb9683 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 @@ -204,6 +204,25 @@ public class KeyStoreReader { return raCertificate; } + public Certificate getCertificateByAlias(String alias) throws KeystoreException { + + KeyStore keystore = loadCertificateKeyStore(); + Certificate raCertificate; + try { + raCertificate = keystore.getCertificate(alias); + } catch (KeyStoreException e) { + String errorMsg = "KeyStore issue occurred when retrieving RA private key"; + log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } + + if (raCertificate == null) { + throw new KeystoreException("RA certificate not found in KeyStore"); + } + + return raCertificate; + } + PrivateKey getRAPrivateKey() throws KeystoreException { KeyStore keystore = loadCertificateKeyStore(); 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 c9b1ca5c96..67171a3f93 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 @@ -33,17 +33,20 @@ public interface CertificateManagementService { Certificate getRACertificate() throws KeystoreException; - public List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException; + List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException; - public X509Certificate generateX509Certificate() throws KeystoreException; + X509Certificate generateX509Certificate() throws KeystoreException; - public SCEPResponse getCACertSCEP() throws KeystoreException; + SCEPResponse getCACertSCEP() throws KeystoreException; - public byte[] getCACapsSCEP(); + byte[] getCACapsSCEP(); - public byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException; + byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException; - public X509Certificate generateCertificateFromCSR(PrivateKey privateKey, - PKCS10CertificationRequest request, + X509Certificate generateCertificateFromCSR(PrivateKey privateKey, PKCS10CertificationRequest request, String issueSubject) throws KeystoreException; + + Certificate getCertificateByAlias(String alias) throws KeystoreException; + + boolean verifySignature(String headerSignature) throws KeystoreException; } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index a294acbc16..014363e90d 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 @@ -84,4 +84,12 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe String issueSubject) throws KeystoreException { return certificateGenerator.generateCertificateFromCSR(privateKey, request, issueSubject); } + + public Certificate getCertificateByAlias(String alias) throws KeystoreException { + return keyStoreReader.getCertificateByAlias(alias); + } + + public boolean verifySignature(String headerSignature) throws KeystoreException { + return certificateGenerator.verifySignature(headerSignature); + } } From 5ee8c0f0654ffee90282f2c66e912884249f8a17 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 2 Sep 2015 14:47:36 +0530 Subject: [PATCH 12/25] Fixing the cache manager issues --- .../operation/mgt/OperationManagerImpl.java | 2 +- .../org.wso2.carbon.policy.mgt.core/pom.xml | 3 +- .../cache/impl/PolicyCacheManagerImpl.java | 233 ++++++++++++++---- .../core/util/PolicyManagementConstants.java | 1 + .../mgt/core/util/PolicyManagerUtil.java | 30 ++- 5 files changed, 212 insertions(+), 57 deletions(-) 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 0315ded100..c26eea0de4 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 @@ -184,7 +184,7 @@ public class OperationManagerImpl implements OperationManager { } finally { DeviceManagementDAOFactory.closeConnection(); } - + OperationManagementDAOFactory.openConnection(); if (enrolmentId < 0) { throw new OperationManagementException("Device not found for the given device Identifier:" + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml index a2333b475d..7e7a50ecd8 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml @@ -71,7 +71,8 @@ org.wso2.carbon.user.api.*, org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.ntask.* + org.wso2.carbon.ntask.*, + org.wso2.carbon.caching.* !org.wso2.carbon.policy.mgt.core.internal, diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java index 677b30920d..28096de9c1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java @@ -27,11 +27,13 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; -import java.util.ArrayList; +import javax.cache.Cache; import java.util.HashMap; +import java.util.Iterator; import java.util.List; -import java.util.Set; public class PolicyCacheManagerImpl implements PolicyCacheManager { @@ -41,6 +43,14 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { private static PolicyCacheManagerImpl policyCacheManager; +// private static Cache getPolicyCache() { +// return PolicyManagerUtil.getPolicyCache(PolicyManagementConstants.DM_CACHE); +// } + + private static Cache> getPolicyListCache() { + return PolicyManagerUtil.getPolicyListCache(PolicyManagementConstants.DM_CACHE_LIST); + } + private PolicyCacheManagerImpl() { } @@ -57,43 +67,87 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void addAllPolicies(List policies) { - HashMap map = this.getTenantRelatedMap(); - if (map.isEmpty()) { - for (Policy policy : policies) { - map.put(policy.getId(), policy); - } - } + // HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// if (cache.isEmpty()) { + +// for (Policy policy : policies) { +// cache.put(policy.getId(), policy); +// } +// } + + Cache> lCache = getPolicyListCache(); + lCache.put(1, policies); } @Override public void updateAllPolicies(List policies) { - HashMap map = this.getTenantRelatedMap(); - map.clear(); - if (map.isEmpty()) { - for (Policy policy : policies) { - map.put(policy.getId(), policy); - } - } +//// HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// cache.removeAll(); +//// map.clear(); +//// if (map.isEmpty()) { +// for (Policy policy : policies) { +//// map.put(policy.getId(), policy); +// cache.put(policy.getId(), policy); +// } +//// } + + Cache> lCache = getPolicyListCache(); + lCache.removeAll(); + lCache.put(1, policies); } @Override public List getAllPolicies() throws PolicyManagementException { - HashMap map = this.getTenantRelatedMap(); - if (map.isEmpty()) { +// // HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// Iterator iterator = cache.iterator(); +//// iterator.hasNext() +// if (!iterator.hasNext()) { +// PolicyManager policyManager = new PolicyManagerImpl(); +// this.addAllPolicies(policyManager.getPolicies()); +// } +// if (log.isDebugEnabled()) { +// //log.debug("No of policies stored in the cache .. : " + map.size()); +// +// //Set keySet = map.keySet(); +// Iterator iterator2 = cache.iterator(); +// while (iterator2.hasNext()) { +// org.wso2.carbon.caching.impl.CacheEntry thisEntry = (org.wso2.carbon.caching.impl.CacheEntry) +// iterator2.next(); +// log.debug("Policy id in maps .. : " + thisEntry.getKey() + " policy name : " + ((Policy) thisEntry +// .getValue()). +// getPolicyName() + " Activated : " + ((Policy) thisEntry.getValue()).isActive()); +// } +// } +// +// List policies = new ArrayList<>(); +// while (iterator.hasNext()){ +// CacheEntry thisEntry = (CacheEntry) iterator.next(); +// policies.add((Policy) thisEntry.getValue()); +// } +// +// return policies; +//// return new ArrayList<>(map.values()); + + Cache> lCache = getPolicyListCache(); + if (!lCache.containsKey(1)) { PolicyManager policyManager = new PolicyManagerImpl(); this.addAllPolicies(policyManager.getPolicies()); } - if (log.isDebugEnabled()) { - log.debug("No of policies stored in the cache .. : " + map.size()); - Set keySet = map.keySet(); - for (Integer x : keySet) { - log.debug("Policy id in maps .. : " + map.get(x).getId() + " policy name : " + map.get(x). - getPolicyName() + " Activated : " + map.get(x).isActive()); + if (log.isDebugEnabled()) { + List cachedPolicy = lCache.get(1); + for (Policy policy : cachedPolicy) { + log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy. + getPolicyName() + " Activated : " + policy.isActive()); } } - return new ArrayList<>(map.values()); + + return lCache.get(1); + } @Override @@ -105,59 +159,136 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void removeAllPolicies() { - HashMap map = this.getTenantRelatedMap(); - map.clear(); +// Cache cache = getPolicyCache(); +// cache.removeAll(); + //HashMap map = this.getTenantRelatedMap(); + //map.clear(); + + Cache> lCache = getPolicyListCache(); + lCache.removeAll(); } @Override public void addPolicy(Policy policy) { - HashMap map = this.getTenantRelatedMap(); - if (!map.containsKey(policy.getId())) { - map.put(policy.getId(), policy); - } else { - log.warn("Policy id (" + policy.getId() + ") already exist in the map. hence not attempted to store."); + //HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// if (!cache.containsKey(policy.getId())) { +// cache.put(policy.getId(), policy); +// } else { +// log.warn("Policy id (" + policy.getId() + ") already exist in the map. hence not attempted to store."); +// } + + Cache> lCache = getPolicyListCache(); + if (lCache.containsKey(1)) { + List cachedPolicy = lCache.get(1); + + for (Policy pol : cachedPolicy) { + if (pol.getId() == policy.getId()) { + return; + } + } + cachedPolicy.add(policy); } + } @Override public void updatePolicy(Policy policy) { - HashMap map = this.getTenantRelatedMap(); - if (map.containsKey(policy.getId())) { - map.remove(policy.getId()); - map.put(policy.getId(), policy); + // HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// if (cache.containsKey(policy.getId())) { +// cache.remove(policy.getId()); +// cache.put(policy.getId(), policy); +// } + + Cache> lCache = getPolicyListCache(); + if (lCache.containsKey(1)) { + List cachedPolicy = lCache.get(1); + Iterator iterator = cachedPolicy.iterator(); + while (iterator.hasNext()) { + Policy pol = (Policy) iterator.next(); + if (pol.getId() == policy.getId()) { + iterator.remove(); + break; + } + } + cachedPolicy.add(policy); + lCache.replace(1, cachedPolicy); } + } @Override public void updatePolicy(int policyId) throws PolicyManagementException { - HashMap map = this.getTenantRelatedMap(); - if (map.containsKey(policyId)) { - this.removePolicy(policyId); + // HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// if (cache.containsKey(policyId)) { +// this.removePolicy(policyId); +// } +// PolicyManager policyManager = new PolicyManagerImpl(); +// Policy policy = policyManager.getPolicy(policyId); +// cache.put(policyId, policy); + + Cache> lCache = getPolicyListCache(); + if (lCache.containsKey(1)) { + PolicyManager policyManager = new PolicyManagerImpl(); + Policy policy = policyManager.getPolicy(policyId); + this.updatePolicy(policy); } - PolicyManager policyManager = new PolicyManagerImpl(); - Policy policy = policyManager.getPolicy(policyId); - map.put(policyId, policy); + } @Override public void removePolicy(int policyId) { - HashMap map = this.getTenantRelatedMap(); - if (map.containsKey(policyId)) { - map.remove(policyId); - } else { - log.warn("Policy id (" + policyId + ") does not exist in the cache. Hence not removed."); + // HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// if (cache.containsKey(policyId)) { +// cache.remove(policyId); +// } else { +// log.warn("Policy id (" + policyId + ") does not exist in the cache. Hence not removed."); +// } + + Cache> lCache = getPolicyListCache(); + if (lCache.containsKey(1)) { + List cachedPolicy = lCache.get(1); + Iterator iterator = cachedPolicy.iterator(); + while (iterator.hasNext()) { + Policy pol = (Policy) iterator.next(); + if (pol.getId() == policyId) { + iterator.remove(); + break; + } + } + lCache.replace(1, cachedPolicy); } } @Override public Policy getPolicy(int policyId) throws PolicyManagementException { - HashMap map = this.getTenantRelatedMap(); - if (!map.containsKey(policyId)) { + //HashMap map = this.getTenantRelatedMap(); +// Cache cache = getPolicyCache(); +// if (!cache.containsKey(policyId)) { +// this.removeAllPolicies(); +// this.getAllPolicies(); +// } +// return cache.get(policyId); + + Cache> lCache = getPolicyListCache(); + if (!lCache.containsKey(1)) { this.removeAllPolicies(); this.getAllPolicies(); } - return map.get(policyId); + Policy policy = null; + List cachedPolicy = lCache.get(1); + Iterator iterator = cachedPolicy.iterator(); + while (iterator.hasNext()) { + Policy pol = (Policy) iterator.next(); + if (pol.getId() == policyId) { + policy = pol; + } + } + return policy; } @Override @@ -175,10 +306,10 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { return 0; } - private HashMap getTenantRelatedMap(){ + private HashMap getTenantRelatedMap() { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - if(!tenantedPolicyMap.containsKey(tenantId)){ + if (!tenantedPolicyMap.containsKey(tenantId)) { HashMap policyMap = new HashMap<>(); tenantedPolicyMap.put(tenantId, policyMap); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java index e8354b3e99..13a2df3442 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java @@ -39,6 +39,7 @@ public final class PolicyManagementConstants { public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER"; public static final String DM_CACHE = "DM_CACHE"; + public static final String DM_CACHE_LIST = "DM_CACHE_LIST"; public static final String DELEGATION_TASK_TYPE = "DELEGATION__TASK"; 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 198913c055..ed14a3c6ea 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 @@ -31,6 +31,10 @@ import org.wso2.carbon.policy.mgt.common.ProfileFeature; import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; +import org.wso2.carbon.registry.api.GhostResource; +import org.wso2.carbon.registry.core.RegistryConstants; +import org.wso2.carbon.registry.core.caching.RegistryCacheEntry; +import org.wso2.carbon.registry.core.caching.RegistryCacheKey; import javax.cache.Cache; import javax.cache.CacheManager; @@ -152,10 +156,28 @@ public class PolicyManagerUtil { } - public static Cache getCacheManagerImpl() { - return Caching.getCacheManagerFactory() - .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants - .DM_CACHE); +// public static Cache getCacheManagerImpl() { +// return Caching.getCacheManagerFactory() +// .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants +// .DM_CACHE); +// } + + + public static Cache getPolicyCache(String name){ + CacheManager manager = getCacheManager(); + return (manager != null) ? manager.getCache(name) : + Caching.getCacheManager().getCache(name); + } + + public static Cache> getPolicyListCache(String name){ + CacheManager manager = getCacheManager(); + return (manager != null) ? manager.>getCache(name) : + Caching.getCacheManager().>getCache(name); + } + + private static CacheManager getCacheManager() { + return Caching.getCacheManagerFactory().getCacheManager( + PolicyManagementConstants.DM_CACHE_MANAGER); } From dff526b27237cf52d1a9f70f75bd6664c2c8b4b9 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 2 Sep 2015 15:02:33 +0530 Subject: [PATCH 13/25] Removing the unnessary commets and imports --- .../cache/impl/PolicyCacheManagerImpl.java | 107 ------------------ .../mgt/core/util/PolicyManagerUtil.java | 4 - 2 files changed, 111 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java index 28096de9c1..624b5ac9d4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java @@ -21,7 +21,6 @@ package org.wso2.carbon.policy.mgt.core.cache.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; @@ -31,7 +30,6 @@ import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import javax.cache.Cache; -import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -39,14 +37,8 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { private static final Log log = LogFactory.getLog(PolicyCacheManagerImpl.class); - private static HashMap> tenantedPolicyMap = new HashMap<>(); - private static PolicyCacheManagerImpl policyCacheManager; -// private static Cache getPolicyCache() { -// return PolicyManagerUtil.getPolicyCache(PolicyManagementConstants.DM_CACHE); -// } - private static Cache> getPolicyListCache() { return PolicyManagerUtil.getPolicyListCache(PolicyManagementConstants.DM_CACHE_LIST); } @@ -67,15 +59,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void addAllPolicies(List policies) { - // HashMap map = this.getTenantRelatedMap(); - -// Cache cache = getPolicyCache(); -// if (cache.isEmpty()) { - -// for (Policy policy : policies) { -// cache.put(policy.getId(), policy); -// } -// } Cache> lCache = getPolicyListCache(); lCache.put(1, policies); @@ -83,16 +66,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void updateAllPolicies(List policies) { -//// HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// cache.removeAll(); -//// map.clear(); -//// if (map.isEmpty()) { -// for (Policy policy : policies) { -//// map.put(policy.getId(), policy); -// cache.put(policy.getId(), policy); -// } -//// } Cache> lCache = getPolicyListCache(); lCache.removeAll(); @@ -101,43 +74,12 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public List getAllPolicies() throws PolicyManagementException { -// // HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// Iterator iterator = cache.iterator(); -//// iterator.hasNext() -// if (!iterator.hasNext()) { -// PolicyManager policyManager = new PolicyManagerImpl(); -// this.addAllPolicies(policyManager.getPolicies()); -// } -// if (log.isDebugEnabled()) { -// //log.debug("No of policies stored in the cache .. : " + map.size()); -// -// //Set keySet = map.keySet(); -// Iterator iterator2 = cache.iterator(); -// while (iterator2.hasNext()) { -// org.wso2.carbon.caching.impl.CacheEntry thisEntry = (org.wso2.carbon.caching.impl.CacheEntry) -// iterator2.next(); -// log.debug("Policy id in maps .. : " + thisEntry.getKey() + " policy name : " + ((Policy) thisEntry -// .getValue()). -// getPolicyName() + " Activated : " + ((Policy) thisEntry.getValue()).isActive()); -// } -// } -// -// List policies = new ArrayList<>(); -// while (iterator.hasNext()){ -// CacheEntry thisEntry = (CacheEntry) iterator.next(); -// policies.add((Policy) thisEntry.getValue()); -// } -// -// return policies; -//// return new ArrayList<>(map.values()); Cache> lCache = getPolicyListCache(); if (!lCache.containsKey(1)) { PolicyManager policyManager = new PolicyManagerImpl(); this.addAllPolicies(policyManager.getPolicies()); } - if (log.isDebugEnabled()) { List cachedPolicy = lCache.get(1); for (Policy policy : cachedPolicy) { @@ -145,7 +87,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { getPolicyName() + " Activated : " + policy.isActive()); } } - return lCache.get(1); } @@ -159,10 +100,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void removeAllPolicies() { -// Cache cache = getPolicyCache(); -// cache.removeAll(); - //HashMap map = this.getTenantRelatedMap(); - //map.clear(); Cache> lCache = getPolicyListCache(); lCache.removeAll(); @@ -170,13 +107,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void addPolicy(Policy policy) { - //HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// if (!cache.containsKey(policy.getId())) { -// cache.put(policy.getId(), policy); -// } else { -// log.warn("Policy id (" + policy.getId() + ") already exist in the map. hence not attempted to store."); -// } Cache> lCache = getPolicyListCache(); if (lCache.containsKey(1)) { @@ -194,12 +124,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void updatePolicy(Policy policy) { - // HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// if (cache.containsKey(policy.getId())) { -// cache.remove(policy.getId()); -// cache.put(policy.getId(), policy); -// } Cache> lCache = getPolicyListCache(); if (lCache.containsKey(1)) { @@ -220,14 +144,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void updatePolicy(int policyId) throws PolicyManagementException { - // HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// if (cache.containsKey(policyId)) { -// this.removePolicy(policyId); -// } -// PolicyManager policyManager = new PolicyManagerImpl(); -// Policy policy = policyManager.getPolicy(policyId); -// cache.put(policyId, policy); Cache> lCache = getPolicyListCache(); if (lCache.containsKey(1)) { @@ -240,13 +156,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public void removePolicy(int policyId) { - // HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// if (cache.containsKey(policyId)) { -// cache.remove(policyId); -// } else { -// log.warn("Policy id (" + policyId + ") does not exist in the cache. Hence not removed."); -// } Cache> lCache = getPolicyListCache(); if (lCache.containsKey(1)) { @@ -265,13 +174,6 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { @Override public Policy getPolicy(int policyId) throws PolicyManagementException { - //HashMap map = this.getTenantRelatedMap(); -// Cache cache = getPolicyCache(); -// if (!cache.containsKey(policyId)) { -// this.removeAllPolicies(); -// this.getAllPolicies(); -// } -// return cache.get(policyId); Cache> lCache = getPolicyListCache(); if (!lCache.containsKey(1)) { @@ -306,13 +208,4 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager { return 0; } - private HashMap getTenantRelatedMap() { - - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (!tenantedPolicyMap.containsKey(tenantId)) { - HashMap policyMap = new HashMap<>(); - tenantedPolicyMap.put(tenantId, policyMap); - } - return tenantedPolicyMap.get(tenantId); - } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/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 ed14a3c6ea..982b3859a7 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 @@ -31,10 +31,6 @@ import org.wso2.carbon.policy.mgt.common.ProfileFeature; import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; -import org.wso2.carbon.registry.api.GhostResource; -import org.wso2.carbon.registry.core.RegistryConstants; -import org.wso2.carbon.registry.core.caching.RegistryCacheEntry; -import org.wso2.carbon.registry.core.caching.RegistryCacheKey; import javax.cache.Cache; import javax.cache.CacheManager; From 46c5dba5c5e1eb4d85031d780063f47f07c974e8 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 2 Sep 2015 15:24:53 +0530 Subject: [PATCH 14/25] Improving web-app authenticator framework --- .../authenticator/framework/APIInfo.java | 24 ----- .../framework/APIMapperContextListener.java | 33 ------- .../WebappAuthenticationHandler.java | 87 +++++++++++++++++++ .../framework/WebappAuthenticatorFactory.java | 17 ++++ .../WebappAuthenticatorFrameworkValve.java | 1 + .../WebappAuthenticatorRepository.java | 9 +- .../authenticator/BasicAuthAuthenticator.java | 19 +++- .../authenticator/JWTAuthenticator.java | 11 ++- .../authenticator/OAuthAuthenticator.java | 26 ++++-- .../WebappAuthenticator.java | 4 +- ...uthenticatorFrameworkServiceComponent.java | 5 +- .../conf/webapp-authenticator-config.xml | 8 ++ 12 files changed, 164 insertions(+), 80 deletions(-) delete mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIInfo.java delete mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIMapperContextListener.java create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java rename components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/{ => authenticator}/WebappAuthenticator.java (89%) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIInfo.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIInfo.java deleted file mode 100644 index 20252f8f5a..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIInfo.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.webapp.authenticator.framework; - -public class APIInfo { - - -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIMapperContextListener.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIMapperContextListener.java deleted file mode 100644 index 21069b6710..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/APIMapperContextListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.webapp.authenticator.framework; - -import org.apache.catalina.Lifecycle; -import org.apache.catalina.LifecycleEvent; -import org.apache.catalina.LifecycleListener; - -public class APIMapperContextListener implements LifecycleListener { - - @Override - public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_INIT_EVENT.equals(lifecycleEvent.getType())) { - } - } - -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java new file mode 100644 index 0000000000..26e0e76d74 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.webapp.authenticator.framework; + +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; +import org.wso2.carbon.tomcat.ext.valves.CompositeValve; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; + +import javax.servlet.http.HttpServletResponse; + +public class WebappAuthenticationHandler extends CarbonTomcatValve { + + private static final Log log = LogFactory.getLog(WebappAuthenticationHandler.class); + + @Override + public void invoke(Request request, Response response, CompositeValve compositeValve) { + if (this.isNonAdminService(request) || this.skipAuthentication(request) || this.isContextSkipped(request)) { + this.getNext().invoke(request, response, compositeValve); + return; + } + WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request); + if (authenticator == null) { + String msg = "Failed to load an appropriate authenticator to authenticate the request"; + AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); + return; + } + WebappAuthenticator.Status status = authenticator.authenticate(request, response); + this.processResponse(request, response, compositeValve, status); + } + + private boolean isNonAdminService(Request request) { + String param = request.getContext().findParameter("isAdminService"); + return !(param != null && Boolean.parseBoolean(param)); + } + + private boolean skipAuthentication(Request request) { + String param = request.getContext().findParameter("doAuthentication"); + return (param == null || !Boolean.parseBoolean(param)); + } + + private boolean isContextSkipped(Request request) { + String ctx = request.getContext().getPath(); + if (ctx == null) { + ctx = request.getContextPath(); + if (ctx == null) { + return false; + } + } + return ctx.equals("/Carbon") || ctx.equals("/Services"); + } + + private void processResponse(Request request, Response response, CompositeValve compositeValve, + WebappAuthenticator.Status status) { + switch (status) { + case SUCCESS: + case CONTINUE: + this.getNext().invoke(request, response, compositeValve); + break; + case FAILURE: + String msg = "Failed to authorize incoming request"; + log.error(msg); + AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); + break; + } + } + +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java index 18758a468b..c0e0e68a49 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java @@ -18,9 +18,26 @@ */ package org.wso2.carbon.webapp.authenticator.framework; +import org.apache.catalina.connector.Request; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; + +import java.util.Map; + public class WebappAuthenticatorFactory { public static WebappAuthenticator getAuthenticator(String authScheme) { return DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme); } + + public static WebappAuthenticator getAuthenticator(Request request) { + Map authenticators = + DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators(); + for (WebappAuthenticator authenticator : authenticators.values()) { + if (authenticator.canHandle(request)) { + return authenticator; + } + } + return null; + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java index d27116b8fe..3501c9e594 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java @@ -24,6 +24,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CompositeValve; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import javax.servlet.http.HttpServletResponse; diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorRepository.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorRepository.java index 02a86ce9cc..bb805c8c76 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorRepository.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorRepository.java @@ -18,15 +18,18 @@ */ package org.wso2.carbon.webapp.authenticator.framework; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; + import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class WebappAuthenticatorRepository { private Map authenticators; public WebappAuthenticatorRepository() { - this.authenticators = new HashMap(); + this.authenticators = new ConcurrentHashMap<>(); } public void addAuthenticator(WebappAuthenticator authenticator) { @@ -37,4 +40,8 @@ public class WebappAuthenticatorRepository { return authenticators.get(name); } + public Map getAuthenticators() { + return authenticators; + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index d17827bd99..7227bdf471 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -24,15 +24,25 @@ import org.apache.catalina.util.Base64; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; -import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator; +import org.wso2.carbon.webapp.authenticator.framework.Constants; public class BasicAuthAuthenticator implements WebappAuthenticator { private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; + private static final String HEADER_BASIC_AUTH = "authorization"; @Override - public boolean isAuthenticated(Request request) { - return false; + public boolean canHandle(Request request) { + MessageBytes authorization = + request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); + if (authorization != null) { + authorization.toBytes(); + ByteChunk authBC = authorization.getByteChunk(); + if (authBC.startsWithIgnoreCase("basic ", 0)) { + return true; + } + } + return false; } @Override @@ -47,7 +57,8 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { private Credentials getCredentials(Request request) { Credentials credentials = null; - MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization"); + MessageBytes authorization = + request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); if (authorization != null) { authorization.toBytes(); ByteChunk authBC = authorization.getByteChunk(); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 20651681f9..974480fd5a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -36,7 +36,6 @@ import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.webapp.authenticator.framework.DataHolder; -import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator; import java.security.interfaces.RSAPublicKey; import java.text.ParseException; @@ -51,12 +50,12 @@ public class JWTAuthenticator implements WebappAuthenticator { public static final String SIGNED_JWT_AUTH_USERNAME = "Username"; private static final String JWT_AUTHENTICATOR = "JWT"; - @Override - public boolean isAuthenticated(Request request) { - return false; - } + @Override + public boolean canHandle(Request request) { + return false; + } - @Override + @Override public Status authenticate(Request request, Response response) { String requestUri = request.getRequestURI(); if (requestUri == null || "".equals(requestUri)) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index cf5a177167..3413cf1b0c 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -30,7 +30,6 @@ import org.wso2.carbon.apimgt.core.gateway.APITokenAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; import org.wso2.carbon.webapp.authenticator.framework.Constants; -import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator; import java.util.StringTokenizer; import java.util.regex.Matcher; @@ -39,13 +38,28 @@ import java.util.regex.Pattern; public class OAuthAuthenticator implements WebappAuthenticator { private static final String OAUTH_AUTHENTICATOR = "OAuth"; - private static APITokenAuthenticator authenticator = new APITokenAuthenticator(); private static final String REGEX_BEARER_PATTERN = "[B|b]earer\\s"; + private static final Pattern PATTERN = Pattern.compile(REGEX_BEARER_PATTERN); + + private static APITokenAuthenticator authenticator = new APITokenAuthenticator(); private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); @Override - public boolean isAuthenticated(Request request) { + public boolean canHandle(Request request) { + MessageBytes authorization = + request.getCoyoteRequest().getMimeHeaders(). + getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); + String tokenValue = null; + if (authorization != null) { + authorization.toBytes(); + ByteChunk authBC = authorization.getByteChunk(); + tokenValue = authBC.toString(); + Matcher matcher = PATTERN.matcher(tokenValue); + if (matcher.find()) { + return true; + } + } return false; } @@ -93,19 +107,15 @@ public class OAuthAuthenticator implements WebappAuthenticator { } private String getBearerToken(Request request) { - MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders(). getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); String tokenValue = null; - if (authorization != null) { - authorization.toBytes(); ByteChunk authBC = authorization.getByteChunk(); tokenValue = authBC.toString(); - Pattern pattern = Pattern.compile(REGEX_BEARER_PATTERN); - Matcher matcher = pattern.matcher(tokenValue); + Matcher matcher = PATTERN.matcher(tokenValue); if (matcher.find()) { tokenValue = tokenValue.substring(matcher.end()); } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java similarity index 89% rename from components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticator.java rename to components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index 5f2eecf8d1..18e49cb212 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.webapp.authenticator.framework; +package org.wso2.carbon.webapp.authenticator.framework.authenticator; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; @@ -27,7 +27,7 @@ public interface WebappAuthenticator { SUCCESS, FAILURE, CONTINUE } - boolean isAuthenticated(Request request); + boolean canHandle(Request request); Status authenticate(Request request, Response response); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index 6dad1613d3..e30d9ce680 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -25,7 +25,8 @@ import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.webapp.authenticator.framework.DataHolder; -import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticator; +import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationHandler; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorFrameworkValve; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepository; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; @@ -64,7 +65,7 @@ public class WebappAuthenticatorFrameworkServiceComponent { DataHolder.getInstance().setWebappAuthenticatorRepository(repository); List valves = new ArrayList(); - valves.add(new WebappAuthenticatorFrameworkValve()); + valves.add(new WebappAuthenticationHandler()); TomcatValveContainer.addValves(valves); if (log.isDebugEnabled()) { diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml index d4c9638d49..f42dde6271 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml @@ -4,5 +4,13 @@ OAuth org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator + + BasicAuth + org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator + + + JWT + org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator + From 0c43338f5db1923eae12c7ad373275024ee9fb2d Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 2 Sep 2015 16:16:18 +0530 Subject: [PATCH 15/25] Added runtime exception to DCA --- .../carbon/device/mgt/common/EnrolmentInfo.java | 13 ++++++------- .../extension/DynamicClientRegistrationUtil.java | 6 +++++- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index a21aa44b91..7b3ff89d1f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.common; import java.io.Serializable; -public class EnrolmentInfo implements Serializable{ +public class EnrolmentInfo implements Serializable { private static final long serialVersionUID = 1998101712L; @@ -40,7 +40,8 @@ public class EnrolmentInfo implements Serializable{ private Status status; private String owner; - public EnrolmentInfo() {} + public EnrolmentInfo() { + } public EnrolmentInfo(Device device, String owner, OwnerShip ownership, Status status) { this.device = device; @@ -109,11 +110,9 @@ public class EnrolmentInfo implements Serializable{ public boolean equals(Object obj) { if (obj instanceof EnrolmentInfo) { EnrolmentInfo tempInfo = (EnrolmentInfo) obj; - if (owner != null && ownership != null) { - if (tempInfo.getOwner() != null && tempInfo.getOwnership() != null) { - if (owner.equals(tempInfo.getOwner()) && ownership.equals(tempInfo.getOwnership())) { - return true; - } + if (this.owner != null && this.ownership != null) { + if (this.owner.equals(tempInfo.getOwner()) && this.ownership.equals(tempInfo.getOwnership())) { + return true; } } } diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java index 0a7698217a..c823323364 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java @@ -128,6 +128,10 @@ public class DynamicClientRegistrationUtil { serviceProvider.setDescription("Service Provider for application " + applicationName); ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + if (appMgtService == null) { + throw new IllegalStateException("Error occurred while retrieving Application Management" + + "Service"); + } appMgtService.createApplication(serviceProvider); ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); @@ -230,7 +234,7 @@ public class DynamicClientRegistrationUtil { ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); if (appMgtService == null) { - throw new APIManagementException("Error occurred while retrieving Application Management" + + throw new IllegalStateException("Error occurred while retrieving Application Management" + "Service"); } ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); From 454c459172aa4092d1767bc5c8aa81f657a5fc99 Mon Sep 17 00:00:00 2001 From: Dilshan Edirisuriya Date: Wed, 2 Sep 2015 16:46:51 +0530 Subject: [PATCH 16/25] Extract certificate from signature --- .../mgt/core/impl/CertificateGenerator.java | 19 +++++++++++-------- .../service/CertificateManagementService.java | 2 ++ .../CertificateManagementServiceImpl.java | 4 ++++ .../certificate/mgt/core/util/CommonUtil.java | 5 +++++ .../pom.xml | 6 +++++- 5 files changed, 27 insertions(+), 9 deletions(-) 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 e0c999ad07..7a2538af22 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 @@ -64,7 +64,6 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; @@ -158,10 +157,9 @@ public class CertificateGenerator { keyPairGenerator.initialize(ConfigurationUtil.RSA_KEY_LENGTH, new SecureRandom()); KeyPair pair = keyPairGenerator.generateKeyPair(); X500Principal principal = new X500Principal(ConfigurationUtil.DEFAULT_PRINCIPAL); - BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( - principal, serial, validityBeginDate, validityEndDate, + principal, CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, principal, pair.getPublic()); ContentSigner contentSigner = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA) .setProvider(ConfigurationUtil.PROVIDER).build( @@ -285,9 +283,14 @@ public class CertificateGenerator { } public boolean verifySignature(String headerSignature) throws KeystoreException { + Certificate certificate = extractCertificateFromSignature(headerSignature); + return (certificate != null); + } + + public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException { if (headerSignature == null || headerSignature.isEmpty()) { - return false; + return null; } try { @@ -308,8 +311,8 @@ public class CertificateGenerator { Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias( reqCert.getSerialNumber().toString()); - if (lookUpCertificate != null) { - return true; + if (lookUpCertificate != null && (lookUpCertificate instanceof X509Certificate)) { + return (X509Certificate)lookUpCertificate; } } @@ -328,7 +331,7 @@ public class CertificateGenerator { throw new KeystoreException(errorMsg, e); } - return false; + return null; } public X509Certificate generateCertificateFromCSR(PrivateKey privateKey, @@ -353,7 +356,7 @@ public class CertificateGenerator { } X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( - new X500Name(issueSubject), BigInteger.valueOf(System.currentTimeMillis()), + new X500Name(issueSubject), CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, certSubject, request.getSubjectPublicKeyInfo()); ContentSigner sigGen; 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 67171a3f93..0b47c43707 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 @@ -49,4 +49,6 @@ public interface CertificateManagementService { Certificate getCertificateByAlias(String alias) throws KeystoreException; boolean verifySignature(String headerSignature) throws KeystoreException; + + public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException; } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 014363e90d..c379df4264 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 @@ -92,4 +92,8 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe public boolean verifySignature(String headerSignature) throws KeystoreException { return certificateGenerator.verifySignature(headerSignature); } + + public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException { + return certificateGenerator.extractCertificateFromSignature(headerSignature); + } } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java index a149c92569..6b9bc5897e 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java @@ -17,6 +17,7 @@ */ package org.wso2.carbon.certificate.mgt.core.util; +import java.math.BigInteger; import java.util.Calendar; import java.util.Date; @@ -40,4 +41,8 @@ public class CommonUtil { return calendar.getTime(); } + public static synchronized BigInteger generateSerialNumber() { + return BigInteger.valueOf(System.currentTimeMillis()); + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 3405148639..edca5ac955 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -88,7 +88,11 @@ org.wso2.carbon.user.core.tenant, org.wso2.carbon.utils, org.wso2.carbon.utils.multitenancy, - org.xml.sax + org.xml.sax, + javax.servlet.http, + javax.xml, + org.apache.axis2.transport.http, + org.wso2.carbon.apimgt.impl From f2635e9e98b4d3132a4bc18c0d92a45a161a77e6 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 2 Sep 2015 18:59:36 +0530 Subject: [PATCH 17/25] Adding more improvements into web-app authenticator framework --- .../framework/WebappAuthenticationHandler.java | 15 ++++++++++----- .../authenticator/BasicAuthAuthenticator.java | 1 - .../authenticator/OAuthAuthenticator.java | 2 +- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java index 26e0e76d74..698c1579b0 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java @@ -27,6 +27,7 @@ import org.wso2.carbon.tomcat.ext.valves.CompositeValve; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import javax.servlet.http.HttpServletResponse; +import java.util.StringTokenizer; public class WebappAuthenticationHandler extends CarbonTomcatValve { @@ -34,7 +35,7 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { @Override public void invoke(Request request, Response response, CompositeValve compositeValve) { - if (this.isNonAdminService(request) || this.skipAuthentication(request) || this.isContextSkipped(request)) { + if (this.isContextSkipped(request) || (this.isNonAdminService(request) && this.skipAuthentication(request))) { this.getNext().invoke(request, response, compositeValve); return; } @@ -60,13 +61,17 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { private boolean isContextSkipped(Request request) { String ctx = request.getContext().getPath(); - if (ctx == null) { + if (ctx == null || "".equals(ctx)) { ctx = request.getContextPath(); - if (ctx == null) { - return false; + if (ctx == null || "".equals(ctx)) { + StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/"); + ctx = tokenizer.nextToken(); + if (ctx == null || "".equals(ctx)) { + return false; + } } } - return ctx.equals("/Carbon") || ctx.equals("/Services"); + return ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services"); } private void processResponse(Request request, Response response, CompositeValve compositeValve, diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 7227bdf471..74396ab9c5 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -29,7 +29,6 @@ import org.wso2.carbon.webapp.authenticator.framework.Constants; public class BasicAuthAuthenticator implements WebappAuthenticator { private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; - private static final String HEADER_BASIC_AUTH = "authorization"; @Override public boolean canHandle(Request request) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 3413cf1b0c..f315919341 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -50,7 +50,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders(). getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); - String tokenValue = null; + String tokenValue; if (authorization != null) { authorization.toBytes(); ByteChunk authBC = authorization.getByteChunk(); From 7dd48bf00efb3121ebcdf7c4a604b016c8c881f1 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 2 Sep 2015 19:39:50 +0530 Subject: [PATCH 18/25] Fixing the monitoring task for INACTIVE, BLOCKED, REMOVED, UNCLAIMED, DISENROLLMENT_REQUESTED, SUSPENDED devices --- .../policy/mgt/core/task/MonitoringTask.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index cff114bf40..2fd0a5b07e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -77,14 +77,13 @@ public class MonitoringTask implements Task { try { - DeviceManagementProviderService deviceManagementProviderService = PolicyManagementDataHolder.getInstance().getDeviceManagementService(); for (DeviceType deviceType : deviceTypes) { - if(log.isDebugEnabled()){ - log.debug("Running task for device type : " + deviceType.getName() ); + if (log.isDebugEnabled()) { + log.debug("Running task for device type : " + deviceType.getName()); } PolicyMonitoringService monitoringService = @@ -100,15 +99,21 @@ public class MonitoringTask implements Task { deviceType.getName()); } for (Device device : devices) { - if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.INACTIVE) || - device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.BLOCKED)) { + EnrolmentInfo.Status status = device.getEnrolmentInfo().getStatus(); + if (status.equals(EnrolmentInfo.Status.INACTIVE) || + status.equals(EnrolmentInfo.Status.BLOCKED) || + status.equals(EnrolmentInfo.Status.REMOVED) || + status.equals(EnrolmentInfo.Status.UNCLAIMED) || + status.equals(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED) || + status.equals(EnrolmentInfo.Status.SUSPENDED)) { continue; } else { notifiableDevices.add(device); } } if (log.isDebugEnabled()) { - log.debug("Following devices selected to send the notification for " + deviceType.getName()); + log.debug("Following devices selected to send the notification for " + + deviceType.getName()); for (Device device : notifiableDevices) { log.debug(device.getDeviceIdentifier()); } From d7ea5625bc5782550b38b784c2fd4456a7e25aa6 Mon Sep 17 00:00:00 2001 From: harshanl Date: Wed, 2 Sep 2015 20:24:33 +0530 Subject: [PATCH 19/25] Fixed apimgt publisher component issues --- .../org.wso2.carbon.apimgt.webapp.publisher/pom.xml | 4 ++++ .../publisher/internal/APIPublisherServiceComponent.java | 5 +++-- .../lifecycle/listener/APIPublisherLifecycleListener.java | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index db99ddb99d..25275cb334 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -52,6 +52,10 @@ + + org.apache.felix + maven-scr-plugin + org.apache.felix maven-bundle-plugin diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 97fe5d11e8..3c47749e03 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -26,11 +26,13 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; +/** + * @scr.component name="org.wso2.carbon.apimgt.webapp.publisher" immediate="true" + */ public class APIPublisherServiceComponent { private static Log log = LogFactory.getLog(APIPublisherServiceComponent.class); - @SuppressWarnings("unused") protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -48,7 +50,6 @@ public class APIPublisherServiceComponent { } } - @SuppressWarnings("unused") protected void deactivate(ComponentContext componentContext) { //do nothing } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index 4284c9a5a5..0078b7c6ff 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -54,7 +54,7 @@ public class APIPublisherLifecycleListener implements LifecycleListener { ServletContext servletContext = context.getServletContext(); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && param.isEmpty()) && Boolean.parseBoolean(param); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); if (isManagedApi) { APIConfig apiConfig = this.buildApiConfig(servletContext); From 4334994b36e82fa96d24a14f5af01bd1aa9f689f Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 2 Sep 2015 20:25:52 +0530 Subject: [PATCH 20/25] Fixing issues encountered in APIPublisher implementation --- .../internal/APIPublisherServiceComponent.java | 1 - .../listener/APIPublisherLifecycleListener.java | 10 ++++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 97fe5d11e8..3e42caf5a0 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -63,7 +63,6 @@ public class APIPublisherServiceComponent { APIPublisherService publisher = new APIPublisherServiceImpl(); APIPublisherDataHolder.getInstance().setApiPublisherService(publisher); bundleContext.registerService(APIPublisherService.class, publisher, null); - } protected void setAPIManagerConfigurationService(APIManagerConfigurationService service) { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index 4284c9a5a5..020925f165 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -26,6 +26,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; +import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; @@ -54,14 +55,19 @@ public class APIPublisherLifecycleListener implements LifecycleListener { ServletContext servletContext = context.getServletContext(); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && param.isEmpty()) && Boolean.parseBoolean(param); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); if (isManagedApi) { APIConfig apiConfig = this.buildApiConfig(servletContext); try { apiConfig.init(); API api = APIPublisherUtil.getAPI(apiConfig); - APIPublisherDataHolder.getInstance().getApiPublisherService().publishAPI(api); + APIPublisherService apiPublisherService = + APIPublisherDataHolder.getInstance().getApiPublisherService(); + if (apiPublisherService == null) { + throw new IllegalStateException("API Publisher service is not initialized properly"); + } + apiPublisherService.publishAPI(api); } catch (Throwable e) { /* Throwable is caught as none of the RuntimeExceptions that can potentially occur at this point does not seem to be logged anywhere else within the framework */ From 256c42243f61233868c584d7aabd4e72f72e57c8 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 2 Sep 2015 21:12:06 +0530 Subject: [PATCH 21/25] Improving APIPublisher implementation --- .../pom.xml | 21 +++++++++++++- .../webapp/publisher/APIPublisherUtil.java | 29 +++++++++++++++++++ .../internal/APIPublisherDataHolder.java | 10 +++++++ .../APIPublisherServiceComponent.java | 21 ++++++++++++++ .../APIPublisherLifecycleListener.java | 8 +++-- 5 files changed, 85 insertions(+), 4 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index 25275cb334..0646ec0551 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -47,6 +47,22 @@ org.wso2.tomcat tomcat-servlet-api + + org.wso2.carbon + org.wso2.carbon.core + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.apache.axis2.wso2 + axis2 + @@ -82,7 +98,10 @@ org.apache.catalina.core, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, - org.wso2.carbon.apimgt.impl + org.wso2.carbon.apimgt.impl, + org.apache.axis2.*;version="${axis2.osgi.version.range}", + org.wso2.carbon.core, + org.wso2.carbon.utils diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index 9776159a61..8a2f782da5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -25,6 +25,10 @@ import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIStatus; import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.ConfigurationContextService; +import org.wso2.carbon.utils.NetworkUtils; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -95,4 +99,29 @@ public class APIPublisherUtil { return uriTemplates; } + public static String getServerBaseUrl() { + // Hostname + String hostName = "localhost"; + try { + hostName = NetworkUtils.getMgtHostName(); + } catch (Exception ignored) { + } + // HTTPS port + String mgtConsoleTransport = CarbonUtils.getManagementTransport(); + ConfigurationContextService configContextService = + APIPublisherDataHolder.getInstance().getConfigurationContextService(); + int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); + int httpsProxyPort = + CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), + mgtConsoleTransport); + if (httpsProxyPort > 0) { + port = httpsProxyPort; + } + return "https://" + hostName + ":" + port; + } + + public static String getApiEndpointUrl(String context) { + return getServerBaseUrl() + context; + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index 41dd3de7ef..833cb5df4f 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -19,10 +19,12 @@ package org.wso2.carbon.apimgt.webapp.publisher.internal; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; +import org.wso2.carbon.utils.ConfigurationContextService; public class APIPublisherDataHolder { private APIPublisherService apiPublisherService; + private ConfigurationContextService configurationContextService; private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); @@ -41,4 +43,12 @@ public class APIPublisherDataHolder { this.apiPublisherService = apiPublisherService; } + public void setConfigurationContextService(ConfigurationContextService configurationContextService) { + this.configurationContextService = configurationContextService; + } + + public ConfigurationContextService getConfigurationContextService() { + return configurationContextService; + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 780bff683b..6d2344a14f 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -25,9 +25,16 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; +import org.wso2.carbon.utils.ConfigurationContextService; /** * @scr.component name="org.wso2.carbon.apimgt.webapp.publisher" immediate="true" + * @scr.reference name="config.context.service" + * interface="org.wso2.carbon.utils.ConfigurationContextService" + * cardinality="0..1" + * policy="dynamic" + * bind="setConfigurationContextService" + * unbind="unsetConfigurationContextService" */ public class APIPublisherServiceComponent { @@ -74,4 +81,18 @@ public class APIPublisherServiceComponent { //do nothing } + protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + APIPublisherDataHolder.getInstance().setConfigurationContextService(configurationContextService); + } + + protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + APIPublisherDataHolder.getInstance().setConfigurationContextService(null); + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index 020925f165..57e520a174 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -54,6 +54,7 @@ public class APIPublisherLifecycleListener implements LifecycleListener { StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); ServletContext servletContext = context.getServletContext(); + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); @@ -116,6 +117,7 @@ public class APIPublisherLifecycleListener implements LifecycleListener { if (log.isDebugEnabled()) { log.debug("'managed-api-endpoint' attribute is not configured"); } + endpoint = APIPublisherUtil.getApiEndpointUrl(context); } apiConfig.setEndpoint(endpoint); @@ -135,10 +137,10 @@ public class APIPublisherLifecycleListener implements LifecycleListener { String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); if (transports == null || transports.isEmpty()) { if (log.isDebugEnabled()) { - log.debug("'managed-api-transports' attribute is not configured. Therefore using the defaults, " + - "which are 'http' and 'https'"); + log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " + + "which is 'https'"); } - transports = "http,https"; + transports = "https"; } apiConfig.setTransports(transports); From dc2680ac5eb0c0520649343e6c130b9b76139ca3 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 2 Sep 2015 21:21:51 +0530 Subject: [PATCH 22/25] Making APIPublisher util compose the relevant API endpoint url programmatically --- .../listener/APIPublisherLifecycleListener.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index 57e520a174..1c425b3c4e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -130,8 +130,16 @@ public class APIPublisherLifecycleListener implements LifecycleListener { apiConfig.setOwner(owner); String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED); - boolean isSecured = - (isSecuredParam != null && !isSecuredParam.isEmpty()) && Boolean.parseBoolean(isSecuredParam); + boolean isSecured; + if (isSecuredParam == null || isSecuredParam.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " + + "which is 'true'"); + } + isSecured = false; + } else { + isSecured = Boolean.parseBoolean(isSecuredParam); + } apiConfig.setSecured(isSecured); String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); From 6ef4bdd73e08e56b0f2b66cbade947c3ee0ac215 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 2 Sep 2015 22:55:52 +0530 Subject: [PATCH 23/25] Fixing enrolment id issues --- .../mgt/common/monitor/ComplianceData.java | 9 ++ .../common/monitor/PolicyDeviceWrapper.java | 51 +++++++++++ .../policy/mgt/core/dao/MonitoringDAO.java | 13 ++- .../mgt/core/dao/impl/MonitoringDAOImpl.java | 89 +++++++++++++++++-- .../core/mgt/impl/MonitoringManagerImpl.java | 62 ++++++++----- 5 files changed, 194 insertions(+), 30 deletions(-) create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/PolicyDeviceWrapper.java diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/ComplianceData.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/ComplianceData.java index 0304e690f0..cb41b1ed9d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/ComplianceData.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/ComplianceData.java @@ -28,6 +28,7 @@ public class ComplianceData { private int id; private int deviceId; + private int enrolmentId; private int policyId; List complianceFeatures; private boolean status; @@ -52,6 +53,14 @@ public class ComplianceData { this.id = id; } + public int getEnrolmentId() { + return enrolmentId; + } + + public void setEnrolmentId(int enrolmentId) { + this.enrolmentId = enrolmentId; + } + public Timestamp getLastRequestedTime() { return lastRequestedTime; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/PolicyDeviceWrapper.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/PolicyDeviceWrapper.java new file mode 100644 index 0000000000..51560bed00 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/monitor/PolicyDeviceWrapper.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.policy.mgt.common.monitor; + +public class PolicyDeviceWrapper { + + private int policyId; + private int deviceId; + private int enrolmentId; + + public int getPolicyId() { + return policyId; + } + + public void setPolicyId(int policyId) { + this.policyId = policyId; + } + + public int getDeviceId() { + return deviceId; + } + + public void setDeviceId(int deviceId) { + this.deviceId = deviceId; + } + + public int getEnrolmentId() { + return enrolmentId; + } + + public void setEnrolmentId(int enrolmentId) { + this.enrolmentId = enrolmentId; + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java index 695ed65f59..522b20f370 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.dao; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; +import org.wso2.carbon.policy.mgt.common.monitor.PolicyDeviceWrapper; import java.util.HashMap; import java.util.List; @@ -35,20 +36,26 @@ public interface MonitoringDAO { * @param devicePolicyMap * @throws MonitoringDAOException */ + + @Deprecated void addComplianceDetails(Map devicePolicyMap) throws MonitoringDAOException; - void setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException; + void addComplianceDetails(List policyDeviceWrappers) throws MonitoringDAOException; + + void setDeviceAsNoneCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException; - void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException; + void setDeviceAsCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException; void addNoneComplianceFeatures(int policyComplianceStatusId, int deviceId, List complianceFeatures) throws MonitoringDAOException; - ComplianceData getCompliance(int deviceId) throws MonitoringDAOException; + ComplianceData getCompliance(int deviceId, int enrolmentId) throws MonitoringDAOException; List getCompliance(List deviceIds) throws MonitoringDAOException; + List getCompliance() throws MonitoringDAOException; + List getNoneComplianceFeatures(int policyComplianceStatusId) throws MonitoringDAOException; void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java index 312988732b..b7d58353d5 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java @@ -24,6 +24,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; +import org.wso2.carbon.policy.mgt.common.monitor.PolicyDeviceWrapper; import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO; import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; @@ -109,7 +110,43 @@ public class MonitoringDAOImpl implements MonitoringDAO { } @Override - public void setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException { + public void addComplianceDetails(List policyDeviceWrapper) throws MonitoringDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet generatedKeys = null; + Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + if (log.isDebugEnabled()) { + for (PolicyDeviceWrapper wrapper : policyDeviceWrapper){ + log.debug("Policy Id : " + wrapper.getPolicyId() + " - " + " Device Id : " + wrapper.getDeviceId()); + } + } + try { + conn = this.getConnection(); + String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " + + "LAST_REQUESTED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?) "; + stmt = conn.prepareStatement(query); + for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) { + stmt.setInt(1, wrapper.getDeviceId()); + stmt.setInt(2, wrapper.getPolicyId()); + stmt.setInt(3, 1); + stmt.setInt(4, 1); + stmt.setTimestamp(5, currentTimestamp); + stmt.setInt(6, tenantId); + stmt.setInt(7, wrapper.getEnrolmentId()); + stmt.addBatch(); + } + stmt.executeBatch(); + } catch (SQLException e) { + throw new MonitoringDAOException("Error occurred while adding the none compliance to the database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); + } + } + + @Override + public void setDeviceAsNoneCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException { Connection conn; PreparedStatement stmt = null; ResultSet generatedKeys = null; @@ -118,12 +155,13 @@ public class MonitoringDAOImpl implements MonitoringDAO { try { conn = this.getConnection(); String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = 0, LAST_FAILED_TIME = ?, POLICY_ID = ?," + - " ATTEMPTS=0 WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + " ATTEMPTS=0 WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setTimestamp(1, currentTimestamp); stmt.setInt(2, policyId); stmt.setInt(3, deviceId); stmt.setInt(4, tenantId); + stmt.setInt(5, enrolmentId); stmt.executeUpdate(); } catch (SQLException e) { @@ -135,7 +173,7 @@ public class MonitoringDAOImpl implements MonitoringDAO { } @Override - public void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException { + public void setDeviceAsCompliance(int deviceId, int enrolmentId, int policyId) throws MonitoringDAOException { Connection conn; PreparedStatement stmt = null; ResultSet generatedKeys = null; @@ -144,12 +182,13 @@ public class MonitoringDAOImpl implements MonitoringDAO { try { conn = this.getConnection(); String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ?, ATTEMPTS=0, LAST_SUCCESS_TIME = ?" + - " WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + " WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setTimestamp(2, currentTimestamp); stmt.setInt(3, deviceId); stmt.setInt(4, tenantId); + stmt.setInt(5, enrolmentId); stmt.executeUpdate(); // generatedKeys = stmt.getGeneratedKeys(); @@ -198,7 +237,7 @@ public class MonitoringDAOImpl implements MonitoringDAO { } @Override - public ComplianceData getCompliance(int deviceId) throws MonitoringDAOException { + public ComplianceData getCompliance(int deviceId, int enrolmentId) throws MonitoringDAOException { Connection conn; PreparedStatement stmt = null; @@ -208,10 +247,11 @@ public class MonitoringDAOImpl implements MonitoringDAO { try { conn = this.getConnection(); - String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); + stmt.setInt(3, enrolmentId); resultSet = stmt.executeQuery(); @@ -253,6 +293,43 @@ public class MonitoringDAOImpl implements MonitoringDAO { ComplianceData complianceData = new ComplianceData(); complianceData.setId(resultSet.getInt("ID")); complianceData.setDeviceId(resultSet.getInt("DEVICE_ID")); + complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID")); + complianceData.setPolicyId(resultSet.getInt("POLICY_ID")); + complianceData.setStatus(resultSet.getBoolean("STATUS")); + complianceData.setAttempts(resultSet.getInt("ATTEMPTS")); + complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME")); + complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME")); + complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME")); + + complianceDataList.add(complianceData); + } + return complianceDataList; + } catch (SQLException e) { + throw new MonitoringDAOException("Unable to retrieve compliance data from database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); + } + } + + @Override + public List getCompliance() throws MonitoringDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + List complianceDataList = new ArrayList<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); + + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + ComplianceData complianceData = new ComplianceData(); + complianceData.setId(resultSet.getInt("ID")); + complianceData.setDeviceId(resultSet.getInt("DEVICE_ID")); + complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID")); complianceData.setPolicyId(resultSet.getInt("POLICY_ID")); complianceData.setStatus(resultSet.getBoolean("STATUS")); complianceData.setAttempts(resultSet.getInt("ATTEMPTS")); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index e3a4d99efa..e72b1d25fa 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -39,10 +39,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceIm import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.ProfileFeature; -import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; -import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint; -import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; -import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; +import org.wso2.carbon.policy.mgt.common.monitor.*; import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService; import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; @@ -98,7 +95,7 @@ public class MonitoringManagerImpl implements MonitoringManager { // run. try { PolicyManagementDAOFactory.openConnection(); - ComplianceData cmd = monitoringDAO.getCompliance(device.getId()); + ComplianceData cmd = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId()); complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, policy, deviceResponse); @@ -118,7 +115,8 @@ public class MonitoringManagerImpl implements MonitoringManager { if (complianceFeatures != null && !complianceFeatures.isEmpty()) { try { PolicyManagementDAOFactory.beginTransaction(); - monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); + monitoringDAO.setDeviceAsNoneCompliance(device.getId(), device.getEnrolmentInfo().getId(), + policy.getId()); if (log.isDebugEnabled()) { log.debug("Compliance status primary key " + complianceData.getId()); } @@ -141,7 +139,8 @@ public class MonitoringManagerImpl implements MonitoringManager { } else { try { PolicyManagementDAOFactory.beginTransaction(); - monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); + monitoringDAO.setDeviceAsCompliance(device.getId(), device.getEnrolmentInfo().getId(), policy + .getId()); monitoringDAO.deleteNoneComplianceData(complianceData.getId()); PolicyManagementDAOFactory.commitTransaction(); } finally { @@ -175,7 +174,8 @@ public class MonitoringManagerImpl implements MonitoringManager { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); PolicyManagementDAOFactory.openConnection(); - ComplianceData complianceData = monitoringDAO.getCompliance(device.getId()); + ComplianceData complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo() + .getId()); if (complianceData == null || !complianceData.isStatus()) { return false; } @@ -203,7 +203,7 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyManagementDAOFactory.openConnection(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); - complianceData = monitoringDAO.getCompliance(device.getId()); + complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId()); List complianceFeatures = monitoringDAO.getNoneComplianceFeatures(complianceData.getId()); complianceData.setComplianceFeatures(complianceFeatures); @@ -228,17 +228,25 @@ public class MonitoringManagerImpl implements MonitoringManager { //int tenantId = PolicyManagerUtil.getTenantId(); Map deviceIds = new HashMap<>(); - List complianceDatas; + List complianceDatas = new ArrayList<>(); HashMap devicePolicyIdMap; - for (Device device : devices) { - deviceIds.put(device.getId(), device); - } - - List deviceIDs = new ArrayList<>(deviceIds.keySet()); try { PolicyManagementDAOFactory.openConnection(); - complianceDatas = monitoringDAO.getCompliance(deviceIDs); + List cd = monitoringDAO.getCompliance(); + + for (Device device : devices) { + deviceIds.put(device.getId(), device); + + for (ComplianceData data : cd) { + if (device.getId() == data.getDeviceId() && device.getEnrolmentInfo().getId() == data + .getEnrolmentId()) { + complianceDatas.add(data); + } + } + } + List deviceIDs = new ArrayList<>(deviceIds.keySet()); + devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs); } catch (SQLException e) { throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); @@ -254,7 +262,9 @@ public class MonitoringManagerImpl implements MonitoringManager { Map deviceIdsWithExistingOperation = new HashMap<>(); Map inactiveDeviceIds = new HashMap<>(); Map deviceToMarkUnreachable = new HashMap<>(); - Map firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); + //Map firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); + + List firstTimeDevices = new ArrayList<>(); Map tempMap = new HashMap<>(); @@ -285,21 +295,31 @@ public class MonitoringManagerImpl implements MonitoringManager { for (Device device : devices) { if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) { deviceIdsToAddOperation.put(device.getId(), device); - firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId())); + + PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper(); + policyDeviceWrapper.setDeviceId(device.getId()); + policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId()); + policyDeviceWrapper.setPolicyId(devicePolicyIdMap.get(device.getId())); + + firstTimeDevices.add(policyDeviceWrapper); + + // firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId())); } } if (log.isDebugEnabled()) { log.debug("These devices are in the system for the first time"); - for (Map.Entry map : firstTimeDeviceIdsWithPolicyIds.entrySet()) { - log.debug("First time device primary key : " + map.getKey() + " & policy id " + map.getValue()); + for (PolicyDeviceWrapper wrapper : firstTimeDevices) { + log.debug("First time device primary key : " + wrapper.getDeviceId() + " & policy id " + + wrapper.getPolicyId()); } } PolicyManagementDAOFactory.beginTransaction(); if (!deviceIdsToAddOperation.isEmpty()) { - monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); +// monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); + monitoringDAO.addComplianceDetails(firstTimeDevices); } if (!deviceIdsWithExistingOperation.isEmpty()) { From 46c5f2534f2d0b76fdd827c007dbe79e8d2ec832 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 3 Sep 2015 00:18:39 +0530 Subject: [PATCH 24/25] Fixing NoSuchElement exception thrown when standard context is accessed --- .../framework/WebappAuthenticationHandler.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java index 698c1579b0..9768344832 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java @@ -64,14 +64,18 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { if (ctx == null || "".equals(ctx)) { ctx = request.getContextPath(); if (ctx == null || "".equals(ctx)) { + String requestUri = request.getRequestURI(); + if ("/".equals(requestUri)) { + return true; + } StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/"); - ctx = tokenizer.nextToken(); - if (ctx == null || "".equals(ctx)) { - return false; + if (!tokenizer.hasMoreTokens()) { + return false; } + ctx = tokenizer.nextToken(); } } - return ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services"); + return (ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services")); } private void processResponse(Request request, Response response, CompositeValve compositeValve, From bbec523a47caf10e3a117283b798b3e729a150ae Mon Sep 17 00:00:00 2001 From: harshanl Date: Thu, 3 Sep 2015 00:19:58 +0530 Subject: [PATCH 25/25] Added notification mechanism --- .../common/notification/mgt/Notification.java | 93 ++++++++ .../mgt/NotificationManagementException.java | 60 +++++ .../mgt/NotificationManagementService.java | 36 +++ ...antConfigurationManagementServiceImpl.java | 5 +- .../carbon/device/mgt/core/dao/DeviceDAO.java | 12 +- .../mgt/core/dao/impl/DeviceDAOImpl.java | 39 +++- .../DeviceManagementServiceComponent.java | 8 + .../NotificationManagementServiceImpl.java | 172 ++++++++++++++ .../notification/mgt/dao/NotificationDAO.java | 83 +++++++ .../dao/NotificationManagementDAOFactory.java | 171 ++++++++++++++ .../mgt/dao/impl/NotificationDAOImpl.java | 214 ++++++++++++++++++ .../mgt/dao/util/NotificationDAOUtil.java | 126 +++++++++++ .../src/main/resources/dbscripts/cdm/h2.sql | 16 +- 13 files changed, 1027 insertions(+), 8 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java new file mode 100644 index 0000000000..0d3af9886d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.notification.mgt; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +/** + * DTO of Notification object which is used to communicate Operation notifications to MDM core. + */ +public class Notification { + + public enum Status{ + NEW, CHECKED + } + + public enum Type{ + ALERT, + } + + private int notificationId; + private DeviceIdentifier deviceIdentifier; + private String description; + private int operationId; + private Status status; + + public Status getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = Status.valueOf(status); + } + + public int getNotificationId() { + return notificationId; + } + + public void setNotificationId(int notificationId) { + this.notificationId = notificationId; + } + + public DeviceIdentifier getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getOperationId() { + return operationId; + } + + public void setOperationId(int operationId) { + this.operationId = operationId; + } + + @Override + public String toString() { + return "Notification{" + + "notificationId='" + notificationId + '\'' + + ", deviceId=" + deviceIdentifier.getId() + + ", deviceType=" + deviceIdentifier.getType() + + ", status=" + status + + ", description='" + description + '\'' + + ", operationId='" + operationId + '\'' + + '}'; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementException.java new file mode 100644 index 0000000000..6de9ac9970 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.notification.mgt; + +/** + * Custom exception class to be used in NotificationMgmt related functionalities. + */ +public class NotificationManagementException extends Exception { + + private static final long serialVersionUID = -8933146283800122660L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public NotificationManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public NotificationManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public NotificationManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public NotificationManagementException() { + super(); + } + + public NotificationManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java new file mode 100644 index 0000000000..730ce6a4de --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.notification.mgt; + +import java.util.List; + +/** + * Defines the contract of NotificationManagementService. + */ +public interface NotificationManagementService { + + public boolean addNotification(Notification notification) throws NotificationManagementException; + public boolean updateNotification(Notification notification) throws NotificationManagementException; + public boolean updateNotificationStatus(int notificationId, Notification.Status status) throws + NotificationManagementException; + public List getAllNotifications() throws NotificationManagementException; + public List getNotificationsByStatus(Notification.Status status) throws + NotificationManagementException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java index 803a53f7ff..61bf277094 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java @@ -36,8 +36,9 @@ import java.io.StringWriter; import java.nio.charset.Charset; /** - * This class implements all the functionality exposed as part of the TenantConfigurationManagementService. Main usage of - * this module is, saving/retrieving tenant configurations to the registry. + * This class implements all the functionality exposed as part of the TenantConfigurationManagementService. + * Main usage of this module is saving/retrieving tenant configurations to the registry. + * */ public class TenantConfigurationManagementServiceImpl implements TenantConfigurationManagementService { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 3eb1f48ac4..261e2e4310 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -63,6 +63,16 @@ public interface DeviceDAO { */ int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve a device of a given device-identifier. + * + * @param deviceIdentifier device id. + * @param tenantId tenant id. + * @return returns the device object. + * @throws DeviceManagementDAOException + */ + Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to retrieve a device of a given id. * @@ -71,7 +81,7 @@ public interface DeviceDAO { * @return returns the device object. * @throws DeviceManagementDAOException */ - Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; + Device getDevice(int deviceId, int tenantId) throws DeviceManagementDAOException; /** * This method is used to retrieve all the devices of a given tenant. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java index 75e916589d..ae9a67f25a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java @@ -102,7 +102,7 @@ public class DeviceDAOImpl implements DeviceDAO { } @Override - public Device getDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException { + public Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -116,8 +116,8 @@ public class DeviceDAOImpl implements DeviceDAO { "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + "AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceId.getType()); - stmt.setString(2, deviceId.getId()); + stmt.setString(1, deviceIdentifier.getType()); + stmt.setString(2, deviceIdentifier.getId()); stmt.setInt(3, tenantId); stmt.setInt(4, tenantId); rs = stmt.executeQuery(); @@ -126,7 +126,38 @@ public class DeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while listing devices for type " + - "'" + deviceId.getType() + "'", e); + "'" + deviceIdentifier.getType() + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return device; + } + + @Override + public Device getDevice(int deviceId, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Device device = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + + "d.ID = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + device = this.loadDevice(rs); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving device for id " + + "'" + deviceId + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 4e54268916..7b34760c80 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -25,6 +25,8 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; @@ -39,6 +41,7 @@ import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -178,6 +181,11 @@ public class DeviceManagementServiceComponent { tenantConfiguration = new TenantConfigurationManagementServiceImpl(); bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null); + /* Registering Notification Service */ + NotificationManagementService notificationManagementService + = new NotificationManagementServiceImpl(); + bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null); + /* Registering App Management service */ try { AppManagementConfigurationManager.getInstance().initConfig(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java new file mode 100644 index 0000000000..3681a026f6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; +import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.SQLException; +import java.util.List; + +/** + * This class implements the NotificationManagementService. + */ +public class NotificationManagementServiceImpl implements NotificationManagementService { + + private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class); + + private NotificationDAO notificationDAO; + private DeviceDAO deviceDAO; + + public NotificationManagementServiceImpl() { + this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO(); + this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); + } + + @Override + public boolean addNotification(Notification notification) throws NotificationManagementException { + boolean status = false; + int deviceId, tenantId; + if (log.isDebugEnabled()) { + log.debug("Adding a Notification : [" + notification.toString() + "]"); + } + try { + tenantId = NotificationDAOUtil.getTenantId(); + DeviceManagementDAOFactory.openConnection(); + Device device = deviceDAO.getDevice(notification.getDeviceIdentifier(), tenantId); + deviceId = device.getId(); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection to" + + " the data source", e); + } catch (DeviceManagementDAOException e) { + throw new NotificationManagementException("Error occurred while retriving device data for " + + " adding notification", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + try { + NotificationManagementDAOFactory.beginTransaction(); + int notificationId = notificationDAO.addNotification(deviceId, tenantId, notification); + NotificationManagementDAOFactory.commitTransaction(); + + if (log.isDebugEnabled()) { + log.debug("Notification id : " + notificationId +" was added to the table."); + } + if(notificationId > 0) { + status = true; + } + } catch (TransactionManagementException e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while adding notification", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + return status; + } + + @Override + public boolean updateNotification(Notification notification) throws NotificationManagementException { + boolean status = false; + if (log.isDebugEnabled()) { + log.debug("Updating Notification : [" + notification.toString() + "]"); + } + try { + NotificationManagementDAOFactory.beginTransaction(); + if(notificationDAO.updateNotification(notification) > 0 ) { + status = true; + } + NotificationManagementDAOFactory.commitTransaction(); + + if (log.isDebugEnabled()) { + log.debug("Notification id : " + notification.getNotificationId() + + " has updated successfully."); + } + } catch (TransactionManagementException e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while updating notification ", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + return status; + } + + @Override + public boolean updateNotificationStatus(int notificationId, Notification.Status status) + throws NotificationManagementException { + boolean operationStatus = false; + if (log.isDebugEnabled()) { + log.debug("Updating Notification id : " + notificationId); + } + try { + NotificationManagementDAOFactory.beginTransaction(); + if(notificationDAO.updateNotificationStatus(notificationId, status) > 0 ) { + operationStatus = true; + } + NotificationManagementDAOFactory.commitTransaction(); + + if (log.isDebugEnabled()) { + log.debug("Notification id : " + notificationId +" has updated successfully."); + } + } catch (TransactionManagementException e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while updating notification", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + return operationStatus; + } + + @Override + public List getAllNotifications() throws NotificationManagementException{ + try { + NotificationManagementDAOFactory.openConnection(); + return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId()); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection to" + + " the data source", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getNotificationsByStatus(Notification.Status status) + throws NotificationManagementException{ + try { + NotificationManagementDAOFactory.openConnection(); + return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId()); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection " + + "to the data source", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java new file mode 100644 index 0000000000..a79bb4fc44 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao; + +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; + +import java.util.List; + +/** + * This class defines the methods to be implemented by NotificationDAO layer. + */ +public interface NotificationDAO { + + /** + * This method is used to add a notification. + * + * @param deviceId device id. + * @param tenantId tenant id. + * @param notification Notification object. + * @return returns the id of the persisted Notification record. + * @throws NotificationManagementException + */ + int addNotification(int deviceId, int tenantId, Notification notification) throws + NotificationManagementException; + + /** + * This method is used to update a notification. + * + * @param notification Notification object. + * @return returns the no of updated records. + * @throws NotificationManagementException + */ + int updateNotification(Notification notification) throws NotificationManagementException; + + /** + * This method is used to update a notification status. + * + * @param notificationId notification id. + * @param status Notification.Status. + * @return returns the no of updated records. + * @throws NotificationManagementException + */ + int updateNotificationStatus(int notificationId, Notification.Status status) + throws NotificationManagementException; + + /** + * This method is used to get all notifications based on tenant-id. + * + * @param tenantId tenant id. + * @return returns the matching notifications. + * @throws NotificationManagementException + */ + List getAllNotifications(int tenantId) throws NotificationManagementException; + + /** + * This method is used to get all notifications based on notification-status. + * + * @param status Notification.Status. + * @param tenantId tenant id. + * @return returns the matching notifications. + * @throws NotificationManagementException + */ + List getNotificationsByStatus(Notification.Status status, int tenantId) throws + NotificationManagementException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java new file mode 100644 index 0000000000..20e8543cb4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; +import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.NotificationDAOImpl; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; + +/** + * DAO factory class to be used in NotificationManagement related functionalities. + */ +public class NotificationManagementDAOFactory { + + private static DataSource dataSource; + private static final Log log = LogFactory.getLog(NotificationManagementDAOFactory.class); + private static ThreadLocal currentConnection = new ThreadLocal(); + + public static NotificationDAO getNotificationDAO() { + return new NotificationDAOImpl(); + } + + public static void init(DataSourceConfig config) { + dataSource = resolveDataSource(config); + } + + public static void init(DataSource dtSource) { + dataSource = dtSource; + } + + public static void beginTransaction() throws TransactionManagementException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + try { + conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void openConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + conn = dataSource.getConnection(); + currentConnection.set(conn); + } + + public static Connection getConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + return conn; + } + + public static void commitTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.commit(); + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + + public static void rollbackTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.rollback(); + } catch (SQLException e) { + log.warn("Error occurred while roll-backing the transaction", e); + } + } + + public static void closeConnection() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while close the connection"); + } + currentConnection.remove(); + } + + + /** + * Resolve data source from the data source definition + * + * @param config data source configuration + * @return data source resolved from the data source definition + */ + private static DataSource resolveDataSource(DataSourceConfig config) { + DataSource dataSource = null; + if (config == null) { + throw new RuntimeException( + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized"); + } + JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); + if (jndiConfig != null) { + if (log.isDebugEnabled()) { + log.debug("Initializing Device Management Repository data source using the JNDI " + + "Lookup Definition"); + } + List jndiPropertyList = + jndiConfig.getJndiProperties(); + if (jndiPropertyList != null) { + Hashtable jndiProperties = new Hashtable(); + for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { + jndiProperties.put(prop.getName(), prop.getValue()); + } + dataSource = NotificationDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); + } else { + dataSource = NotificationDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null); + } + } + return dataSource; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java new file mode 100644 index 0000000000..ab1152dc92 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +/** + * Implementation of NotificationDAO which includes the methods to do CRUD operations on notification. + */ +public class NotificationDAOImpl implements NotificationDAO { + + private static final Log log = LogFactory.getLog(NotificationDAOImpl.class); + + @Override + public int addNotification(int deviceId, int tenantId, Notification notification) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt; + ResultSet rs; + int notificationId = -1; + try { + NotificationManagementDAOFactory.beginTransaction(); + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?)"; + stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + stmt.setInt(1, deviceId); + stmt.setInt(2, notification.getOperationId()); + stmt.setString(3, notification.getStatus().toString()); + stmt.setString(4, notification.getDescription()); + stmt.setInt(5, tenantId); + stmt.execute(); + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + notificationId = rs.getInt(1); + } + NotificationManagementDAOFactory.commitTransaction(); + } catch (Exception e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while adding the " + + "Notification for device id : " + deviceId, + e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + return notificationId; + } + + @Override + public int updateNotification(Notification notification) + throws NotificationManagementException { + Connection conn; + PreparedStatement stmt; + int rows; + try { + NotificationManagementDAOFactory.beginTransaction(); + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " + + "WHERE NOTIFICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, notification.getOperationId()); + stmt.setString(2, notification.getStatus().toString()); + stmt.setString(3, notification.getDescription()); + stmt.setInt(4, notification.getNotificationId()); + rows = stmt.executeUpdate(); + NotificationManagementDAOFactory.commitTransaction(); + } catch (Exception e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while updating the " + + "Notification id : " + notification.getNotificationId(), e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + return rows; + } + + @Override + public int updateNotificationStatus(int notificationId, Notification.Status status) + throws NotificationManagementException { + Connection conn; + PreparedStatement stmt; + int rows; + try { + NotificationManagementDAOFactory.beginTransaction(); + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, status.toString()); + stmt.setInt(2, notificationId); + rows = stmt.executeUpdate(); + NotificationManagementDAOFactory.commitTransaction(); + } catch (Exception e) { + NotificationManagementDAOFactory.rollbackTransaction(); + throw new NotificationManagementException("Error occurred while updating the status of " + + "Notification id : " + notificationId, e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + return rows; + } + + @Override + public List getAllNotifications(int tenantId) + throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(this.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + @Override + public List getNotificationsByStatus(Notification.Status status, int tenantId) + throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(this.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + private Notification getNotification(ResultSet rs) throws SQLException { + Notification notification = new Notification(); + notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); + notification.setDeviceIdentifier(this.getDeviceIdentifier(rs)); + notification.setOperationId(rs.getInt("OPERATION_ID")); + notification.setDescription(rs.getString("DESCRIPTION")); + notification.setStatus(rs.getString("STATUS")); + return notification; + } + + private DeviceIdentifier getDeviceIdentifier(ResultSet rs) throws SQLException { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + identifier.setType(rs.getString("DEVICE_TYPE")); + return identifier; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java new file mode 100644 index 0000000000..5c87e1b311 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.tenant.TenantManager; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Hashtable; + +/** + * This class includes the utility methods required by NotificationMgmt functionalities. + */ +public class NotificationDAOUtil { + + private static final Log log = LogFactory.getLog(NotificationDAOUtil.class); + + public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing database connection", e); + } + } + } + + public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + } + + /** + * Get id of the current tenant. + * + * @return tenant id + * @throws org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException if an error is observed when getting tenant id + */ + public static int getTenantId() throws NotificationManagementException { + CarbonContext context = CarbonContext.getThreadLocalCarbonContext(); + int tenantId = context.getTenantId(); + if (tenantId != MultitenantConstants.INVALID_TENANT_ID) { + return tenantId; + } + String tenantDomain = context.getTenantDomain(); + if (tenantDomain == null) { + String msg = "Tenant domain is not properly set and thus, is null"; + throw new NotificationManagementException(msg); + } + TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager(); + try { + tenantId = tenantManager.getTenantId(tenantDomain); + } catch (UserStoreException e) { + String msg = + "Error occurred while retrieving id from the domain of tenant " + tenantDomain; + throw new NotificationManagementException(msg); + } + return tenantId; + } + + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } +} diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 781ea7640b..8ce7795373 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -382,9 +382,23 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); - -- POLICY RELATED TABLES FINISHED -- +-- NOTIFICATION TABLE -- +CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( + NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(100) NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); +-- NOTIFICATION TABLE END -- -- TO:DO - Remove this INSERT sql statement. --Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android');