revert-70aa11f8
mharindu 10 years ago
commit af18323f4e

@ -17,9 +17,10 @@
*/
package org.wso2.carbon.device.mgt.common;
import java.io.Serializable;
import java.util.List;
public class Feature {
public class Feature implements Serializable{
private int id;
private String code;

@ -19,12 +19,10 @@
package org.wso2.carbon.policy.evaluator;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.List;
import java.util.Map;
public interface FeatureFilter {

@ -19,7 +19,6 @@
package org.wso2.carbon.policy.evaluator;
import org.wso2.carbon.policy.evaluator.utils.Constants;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
@ -103,17 +102,17 @@ public class FeatureFilterImpl implements FeatureFilter {
*/
public void getDenyOverridesFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
ProfileFeature evaluatedFeature = null;
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
if (feature.getFeature().getRuleValue().equalsIgnoreCase("Deny")) {
evaluatedFeature = feature;
effectiveFeatureList.add(evaluatedFeature);
return;
} else {
evaluatedFeature = feature;
}
}
}
// for (ProfileFeature feature : featureList) {
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// if (feature.getFeature().getRuleValue().equalsIgnoreCase("Deny")) {
// evaluatedFeature = feature;
// effectiveFeatureList.add(evaluatedFeature);
// return;
// } else {
// evaluatedFeature = feature;
// }
// }
// }
if (evaluatedFeature != null) {
effectiveFeatureList.add(evaluatedFeature);
}
@ -130,17 +129,17 @@ public class FeatureFilterImpl implements FeatureFilter {
*/
public void getPermitOverridesFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
ProfileFeature evaluatedFeature = null;
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
if (feature.getFeature().getRuleValue().equalsIgnoreCase("Permit")) {
evaluatedFeature = feature;
effectiveFeatureList.add(evaluatedFeature);
return;
} else {
evaluatedFeature = feature;
}
}
}
// for (ProfileFeature feature : featureList) {
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// if (feature.getFeature().getRuleValue().equalsIgnoreCase("Permit")) {
// evaluatedFeature = feature;
// effectiveFeatureList.add(evaluatedFeature);
// return;
// } else {
// evaluatedFeature = feature;
// }
// }
// }
if (evaluatedFeature != null) {
effectiveFeatureList.add(evaluatedFeature);
}
@ -157,11 +156,11 @@ public class FeatureFilterImpl implements FeatureFilter {
*/
public void getFirstApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
effectiveFeatureList.add(feature);
return;
}
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// effectiveFeatureList.add(feature);
// return;
//
// }
}
}
@ -175,11 +174,11 @@ public class FeatureFilterImpl implements FeatureFilter {
*/
public void getLastApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
ProfileFeature evaluatedFeature = null;
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
evaluatedFeature = feature;
}
}
// for (ProfileFeature feature : featureList) {
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// evaluatedFeature = feature;
// }
// }
if (evaluatedFeature != null) {
effectiveFeatureList.add(evaluatedFeature);
}
@ -195,9 +194,9 @@ public class FeatureFilterImpl implements FeatureFilter {
*/
public void getAllApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
effectiveFeatureList.add(feature);
}
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// effectiveFeatureList.add(feature);
// }
}
}
@ -212,14 +211,14 @@ public class FeatureFilterImpl implements FeatureFilter {
public void getHighestApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
ProfileFeature evaluatedFeature = null;
int intValve = 0;
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
if (Integer.parseInt(feature.getFeature().getRuleValue()) > intValve) {
intValve = Integer.parseInt(feature.getFeature().getRuleValue());
evaluatedFeature = feature;
}
}
}
// for (ProfileFeature feature : featureList) {
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// if (Integer.parseInt(feature.getFeature().getRuleValue()) > intValve) {
// intValve = Integer.parseInt(feature.getFeature().getRuleValue());
// evaluatedFeature = feature;
// }
// }
// }
if (evaluatedFeature != null) {
effectiveFeatureList.add(evaluatedFeature);
}
@ -235,15 +234,15 @@ public class FeatureFilterImpl implements FeatureFilter {
*/
public void getLowestApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
ProfileFeature evaluatedFeature = null;
int intValve = 0;
for (ProfileFeature feature : featureList) {
if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
if (Integer.parseInt(feature.getFeature().getRuleValue()) < intValve) {
intValve = Integer.parseInt(feature.getFeature().getRuleValue());
evaluatedFeature = feature;
}
}
}
// int intValve = 0;
// for (ProfileFeature feature : featureList) {
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
// if (Integer.parseInt(feature.getFeature().getRuleValue()) < intValve) {
// intValve = Integer.parseInt(feature.getFeature().getRuleValue());
// evaluatedFeature = feature;
// }
// }
// }
if (evaluatedFeature != null) {
effectiveFeatureList.add(evaluatedFeature);
}

@ -39,7 +39,7 @@ public class PolicyFilterImpl implements PolicyFilter {
List<Policy> policies = new ArrayList<Policy>();
for (Policy policy : policyList) {
List<String> roleList = policy.getRoleList();
List<String> roleList = policy.getRoles();
for (String role : roleList) {
if (roles.contains(role)) {

@ -19,7 +19,7 @@
package org.wso2.carbon.policy.information.point;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.PIPDevice;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;

@ -56,7 +56,8 @@
<Import-Package>
org.apache.commons.logging,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.core.dto.*
org.wso2.carbon.device.mgt.core.dto.*,
javax.xml.bind.*,
</Import-Package>
<Export-Package>
org.wso2.carbon.policy.mgt.common.*

@ -0,0 +1,42 @@
/*
* 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;
public class Criterion {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

@ -22,67 +22,67 @@ import java.io.Serializable;
public class Feature implements Serializable {
private int id;
private String code;
private String name;
private String description;
// private Object attribute;
private String ruleValue;
private int deviceTypeId;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/* public Object getAttribute() {
return attribute;
}
public void setAttribute(Object attribute) {
this.attribute = attribute;
}*/
public int getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(int deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
// private int id;
// private String code;
// private String name;
// private String description;
// // private Object attribute;
// private String ruleValue;
// private int deviceTypeId;
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getRuleValue() {
// return ruleValue;
// }
//
// public void setRuleValue(String ruleValue) {
// this.ruleValue = ruleValue;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
///* public Object getAttribute() {
// return attribute;
// }
//
// public void setAttribute(Object attribute) {
// this.attribute = attribute;
// }*/
//
// public int getDeviceTypeId() {
// return deviceTypeId;
// }
//
// public void setDeviceTypeId(int deviceTypeId) {
// this.deviceTypeId = deviceTypeId;
// }
}

@ -21,6 +21,8 @@ package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.core.dto.Device;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.sql.Date;
import java.util.List;
@ -29,6 +31,7 @@ import java.util.Map;
/**
* This class will be the used to create policy object with relevant information for evaluating.
*/
@XmlRootElement
public class Policy implements Comparable<Policy>, Serializable {
private int id; // Identifier of the policy.
@ -36,13 +39,17 @@ public class Policy implements Comparable<Policy>, Serializable {
private Profile profile; // Profile
private String policyName; // Name of the policy.
private boolean generic; // If true, this should be applied to all related device.
private List<String> roleList; // Roles which this policy should be applied.
private List<String> roles; // Roles which this policy should be applied.
private String ownershipType; // Ownership type (COPE, BYOD, CPE)
private List<Device> DeviceList; // Individual devices this policy should be applied
private List<Device> devices; // Individual devices this policy should be applied
private List<String> users;
/*Dynamic policy attributes*/
/* This is related criteria based policy */
private List<PolicyCriteria> policyCriterias;
/*These are related to time based policies*/
private int startTime; // Start time to apply the policy.
@ -63,6 +70,7 @@ public class Policy implements Comparable<Policy>, Serializable {
private Map<String, Object> attributes;
@XmlElement
public int getId() {
return id;
}
@ -71,6 +79,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.id = id;
}
@XmlElement
public int getPriorityId() {
return priorityId;
}
@ -79,6 +88,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.priorityId = priorityId;
}
@XmlElement
public Profile getProfile() {
return profile;
}
@ -87,6 +97,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.profile = profile;
}
@XmlElement
public int getProfileId() {
return profileId;
}
@ -95,6 +106,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.profileId = profileId;
}
@XmlElement
public String getPolicyName() {
return policyName;
}
@ -103,6 +115,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.policyName = policyName;
}
@XmlElement
public boolean isGeneric() {
return generic;
}
@ -111,14 +124,16 @@ public class Policy implements Comparable<Policy>, Serializable {
this.generic = generic;
}
public List<String> getRoleList() {
return roleList;
@XmlElement
public List<String> getRoles() {
return roles;
}
public void setRoleList(List<String> roleList) {
this.roleList = roleList;
public void setRoles(List<String> roles) {
this.roles = roles;
}
@XmlElement
public String getOwnershipType() {
return ownershipType;
}
@ -127,14 +142,16 @@ public class Policy implements Comparable<Policy>, Serializable {
this.ownershipType = ownershipType;
}
public List<Device> getDeviceList() {
return DeviceList;
@XmlElement
public List<Device> getDevices() {
return devices;
}
public void setDeviceList(List<Device> deviceList) {
DeviceList = deviceList;
public void setDevices(List<Device> devices) {
this.devices = devices;
}
@XmlElement
public List<String> getUsers() {
return users;
}
@ -143,6 +160,15 @@ public class Policy implements Comparable<Policy>, Serializable {
this.users = users;
}
@XmlElement
public List<PolicyCriteria> getPolicyCriterias() {
return policyCriterias;
}
public void setPolicyCriterias(List<PolicyCriteria> policyCriterias) {
this.policyCriterias = policyCriterias;
}
public int getStartTime() {
return startTime;
}
@ -151,6 +177,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.startTime = startTime;
}
@XmlElement
public int getEndTime() {
return endTime;
}
@ -159,6 +186,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.endTime = endTime;
}
@XmlElement
public Date getStartDate() {
return startDate;
}
@ -167,6 +195,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.startDate = startDate;
}
@XmlElement
public Date getEndDate() {
return endDate;
}
@ -175,6 +204,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.endDate = endDate;
}
@XmlElement
public String getLatitude() {
return latitude;
}
@ -183,6 +213,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.latitude = latitude;
}
@XmlElement
public String getLongitude() {
return longitude;
}
@ -191,6 +222,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.longitude = longitude;
}
@XmlElement
public Map<String, Object> getAttributes() {
return attributes;
}
@ -199,6 +231,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.attributes = attributes;
}
@XmlElement
public int getTenantId() {
return tenantId;
}

@ -17,7 +17,7 @@
*/
package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List;
@ -131,6 +131,10 @@ public interface PolicyAdministratorPoint {
Profile updateProfile(Profile profile) throws PolicyManagementException;
Profile getProfile(int profileId) throws PolicyManagementException;
List<Profile> getProfiles() throws PolicyManagementException;
Feature addFeature(Feature feature) throws FeatureManagementException;
Feature updateFeature(Feature feature) throws FeatureManagementException;

@ -0,0 +1,63 @@
/*
* 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;
import java.util.Map;
import java.util.Properties;
public class PolicyCriteria {
private int id;
private String name;
private Properties properties;
private Map<String, Object> objectMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Map<String, Object> getObjectMap() {
return objectMap;
}
public void setObjectMap(Map<String, Object> objectMap) {
this.objectMap = objectMap;
}
}

@ -20,6 +20,7 @@
package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature;
import java.util.List;

@ -22,9 +22,11 @@ package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.sql.Timestamp;
import java.util.List;
@XmlRootElement
public class Profile {
private int profileId;
@ -43,7 +45,7 @@ public class Profile {
public void setDeviceType(DeviceType deviceType) {
this.deviceType = deviceType;
}
@XmlElement
public int getTenantId() {
return tenantId;
}
@ -59,7 +61,7 @@ public class Profile {
public void setFeaturesList(List<Feature> featuresList) {
this.featuresList = featuresList;
}*/
@XmlElement
public int getProfileId() {
return profileId;
}
@ -68,6 +70,7 @@ public class Profile {
this.profileId = profileId;
}
@XmlElement
public String getProfileName() {
return profileName;
}
@ -76,6 +79,7 @@ public class Profile {
this.profileName = profileName;
}
@XmlElement
public Timestamp getCreatedDate() {
return createdDate;
}
@ -84,6 +88,7 @@ public class Profile {
this.createdDate = createdDate;
}
@XmlElement
public Timestamp getUpdatedDate() {
return updatedDate;
}
@ -92,6 +97,7 @@ public class Profile {
this.updatedDate = updatedDate;
}
@XmlElement
public List<ProfileFeature> getProfileFeaturesList() {
return profileFeaturesList;
}

@ -19,12 +19,15 @@
package org.wso2.carbon.policy.mgt.common;
import java.io.Serializable;
import org.wso2.carbon.device.mgt.common.Feature;
public class ProfileFeature implements Serializable {
private int id;
private Feature feature;
private String featureCode;
// private Feature feature;
private int profileId;
private int deviceTypeId;
private Object content;
public int getId() {
@ -35,14 +38,22 @@ public class ProfileFeature implements Serializable {
this.id = id;
}
public Feature getFeature() {
return feature;
public String getFeatureCode() {
return featureCode;
}
public void setFeature(Feature feature) {
this.feature = feature;
public void setFeatureCode(String featureCode) {
this.featureCode = featureCode;
}
// public Feature getFeature() {
// return feature;
// }
//
// public void setFeature(Feature feature) {
// this.feature = feature;
// }
public int getProfileId() {
return profileId;
}
@ -51,6 +62,14 @@ public class ProfileFeature implements Serializable {
this.profileId = profileId;
}
public int getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(int deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
public Object getContent() {
return content;
}

@ -18,7 +18,8 @@
package org.wos2.carbon.policy.mgt.common.utils;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.Profile;

@ -20,7 +20,15 @@
package org.wso2.carbon.policy.mgt.core;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.List;

@ -21,7 +21,16 @@ package org.wso2.carbon.policy.mgt.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.impl.PolicyInformationPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;

@ -19,8 +19,7 @@
package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;

@ -18,7 +18,6 @@
package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.policy.mgt.common.*;
@ -43,6 +42,24 @@ public interface PolicyDAO {
Policy addLocationToPolicy(String latitude, String longitude, Policy policy) throws PolicyManagerDAOException;
Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException;
Criterion updateCriterion(Criterion criteria) throws PolicyManagerDAOException;
Criterion getCriterion(int id) throws PolicyManagerDAOException;
Criterion getCriterion(String name) throws PolicyManagerDAOException;
boolean checkCriterionExists(String name) throws PolicyManagerDAOException;
boolean deleteCriterion(Criterion criteria) throws PolicyManagerDAOException;
List<Criterion> getAllPolicyCriteria() throws PolicyManagerDAOException;
Policy addPolicyCriteria(Policy policy) throws PolicyManagerDAOException;
List<PolicyCriteria> getPolicyCriteria(int policyId) throws PolicyManagerDAOException;
Policy updatePolicy(Policy policy) throws PolicyManagerDAOException;
Policy getPolicy(int policyId) throws PolicyManagerDAOException;

@ -1,10 +1,10 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -15,13 +15,12 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.webapp.authenticator.framework;
public class HandlerConstants {
public static final String HEADER_AUTHORIZATION = "Authorization";
public static final String TOKEN_NAME_BEARER = "Bearer";
package org.wso2.carbon.policy.mgt.core.dao.dto;
public static final String NO_MATCHING_AUTH_SCHEME = "noMatchedAuthScheme";
public class PolicyCriteriaDTO {
private int id;
private String name;
}

@ -20,7 +20,8 @@ package org.wso2.carbon.policy.mgt.core.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO;
@ -50,13 +51,13 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_FEATURES (NAME, CODE, DESCRIPTION, EVALUATION_RULE, DEVICE_TYPE_ID) VALUES (?, ?, ?, ?, ?)";
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());
stmt.setString(4, feature.getRuleValue());
stmt.setInt(5, feature.getDeviceTypeId());
// stmt.setString(4, feature.getRuleValue());
// stmt.setInt(5, feature.getDeviceTypeId());
int affectedRows = stmt.executeUpdate();
if (log.isDebugEnabled()) {
@ -88,15 +89,15 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_FEATURES (NAME, CODE, DESCRIPTION, EVALUATION_RULE, DEVICE_TYPE_ID) VALUES (?, ?, ?, ?, ?)";
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.setString(4, feature.getRuleValue());
stmt.setInt(5, feature.getDeviceTypeId());
// stmt.setString(4, feature.getRuleValue());
// stmt.setInt(5, feature.getDeviceTypeId());
stmt.addBatch();
}
@ -133,13 +134,13 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "UPDATE DM_FEATURES SET NAME = ?, CODE = ?, DESCRIPTION = ?, EVALUATION_RULE = ? WHERE ID = ?";
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.setString(4, feature.getRuleValue());
stmt.setInt(5, feature.getId());
// stmt.setString(4, feature.getRuleValue());
stmt.setInt(4, feature.getId());
stmt.executeUpdate();
} catch (SQLException e) {
@ -172,13 +173,15 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_PROFILE_FEATURES (PROFILE_ID, FEATURE_ID, CONTENT) VALUES (?, ?, ?)";
String query = "INSERT INTO DM_PROFILE_FEATURES (PROFILE_ID, FEATURE_CODE, DEVICE_TYPE_ID, CONTENT) " +
"VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
for (ProfileFeature feature : features) {
stmt.setInt(1, profileId);
stmt.setInt(2, feature.getFeature().getId());
stmt.setObject(3, feature.getContent());
stmt.setString(2, feature.getFeatureCode());
stmt.setInt(3, feature.getDeviceTypeId());
stmt.setObject(4, feature.getContent());
stmt.addBatch();
//Not adding the logic to check the size of the stmt and execute if the size records added is over 1000
}
@ -210,13 +213,13 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "UPDATE DM_PROFILE_FEATURES SET CONTENT = ? WHERE PROFILE_ID = ? , FEATURE_ID = ? ";
String query = "UPDATE DM_PROFILE_FEATURES SET CONTENT = ? WHERE PROFILE_ID = ?, FEATURE_CODE = ?";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
for (ProfileFeature feature : features) {
stmt.setObject(1, feature.getContent());
stmt.setInt(2, profileId);
stmt.setInt(3, feature.getFeature().getId());
stmt.setString(3, feature.getFeatureCode());
stmt.addBatch();
//Not adding the logic to check the size of the stmt and execute if the size records added is over 1000
}
@ -259,36 +262,36 @@ public class FeatureDAOImpl implements FeatureDAO {
@Override
public List<Feature> getAllFeatures() throws FeatureManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
// Connection conn;
// PreparedStatement stmt = null;
// ResultSet resultSet = null;
List<Feature> featureList = new ArrayList<Feature>();
try {
conn = this.getConnection();
String query = "SELECT ID, NAME, CODE, DEVICE_TYPE_ID, EVALUATION_RULE FROM DM_FEATURES";
stmt = conn.prepareStatement(query);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
Feature feature = new Feature();
feature.setId(resultSet.getInt("ID"));
feature.setCode(resultSet.getString("CODE"));
feature.setName(resultSet.getString("NAME"));
feature.setDeviceTypeId(resultSet.getInt("DEVICE_TYPE_ID"));
feature.setRuleValue(resultSet.getString("EVALUATION_RULE"));
featureList.add(feature);
}
} catch (SQLException e) {
String msg = "Unable to get the list of the features from database.";
log.error(msg);
throw new FeatureManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
this.closeConnection();
}
//
// try {
// conn = this.getConnection();
// String query = "SELECT ID, NAME, CODE, DEVICE_TYPE_ID, EVALUATION_RULE FROM DM_FEATURES";
// stmt = conn.prepareStatement(query);
// resultSet = stmt.executeQuery();
//
// while (resultSet.next()) {
//
// Feature feature = new Feature();
// feature.setId(resultSet.getInt("ID"));
// feature.setCode(resultSet.getString("CODE"));
// feature.setName(resultSet.getString("NAME"));
// feature.setDeviceTypeId(resultSet.getInt("DEVICE_TYPE_ID"));
// feature.setRuleValue(resultSet.getString("EVALUATION_RULE"));
// featureList.add(feature);
// }
//
// } catch (SQLException e) {
// String msg = "Unable to get the list of the features from database.";
// log.error(msg);
// throw new FeatureManagerDAOException(msg, e);
// } finally {
// PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
// this.closeConnection();
// }
return featureList;
}
@ -302,22 +305,22 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "SELECT PF.ID AS ID, PF.FEATURE_ID FEATURE_ID, F.NAME NAME, F.CODE CODE, " +
"F.EVALUATION_RULE RULE, PF.CONTENT AS CONTENT, PF.PROFILE_ID PROFILE_ID FROM DM_PROFILE_FEATURES AS PF " +
"JOIN DM_FEATURES AS F ON F.ID = PF.FEATURE_ID";
String query = "SELECT ID, PROFILE_ID, FEATURE_CODE, DEVICE_TYPE_ID, CONTENT FROM DM_PROFILE_FEATURES";
stmt = conn.prepareStatement(query);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
ProfileFeature profileFeature = new ProfileFeature();
Feature feature = new Feature();
feature.setId(resultSet.getInt("FEATURE_ID"));
feature.setCode(resultSet.getString("CODE"));
feature.setName(resultSet.getString("NAME"));
feature.setRuleValue(resultSet.getString("RULE"));
profileFeature.setFeature(feature);
// Feature feature = new Feature();
// feature.setId(resultSet.getInt("FEATURE_ID"));
// feature.setCode(resultSet.getString("CODE"));
// feature.setName(resultSet.getString("NAME"));
// feature.setRuleValue(resultSet.getString("RULE"));
// profileFeature.setFeature(feature);
profileFeature.setFeatureCode(resultSet.getString("FEATURE_CODE"));
profileFeature.setDeviceTypeId(resultSet.getInt("DEVICE_TYPE_ID"));
profileFeature.setId(resultSet.getInt("ID"));
profileFeature.setContent(resultSet.getObject("CONTENT"));
profileFeature.setProfileId(resultSet.getInt("PROFILE_ID"));
@ -358,8 +361,8 @@ public class FeatureDAOImpl implements FeatureDAO {
feature.setId(resultSet.getInt("ID"));
feature.setCode(resultSet.getString("CODE"));
feature.setName(resultSet.getString("NAME"));
feature.setDeviceTypeId(resultSet.getInt("DEVICE_TYPE_ID"));
feature.setRuleValue(resultSet.getString("EVALUATION_RULE"));
// feature.setDeviceTypeId(resultSet.getInt("DEVICE_TYPE_ID"));
// feature.setRuleValue(resultSet.getString("EVALUATION_RULE"));
featureList.add(feature);
}
@ -384,23 +387,24 @@ public class FeatureDAOImpl implements FeatureDAO {
try {
conn = this.getConnection();
String query = "SELECT PF.ID AS ID, PF.FEATURE_ID FEATURE_ID, F.NAME NAME, F.CODE CODE, " +
"F.EVALUATION_RULE RULE, F.CONTENT AS CONTENT FROM DM_PROFILE_FEATURES AS PF " +
"JOIN DM_FEATURES AS F ON F.ID = PF.FEATURE_ID WHERE PROFILE_ID=?";
String query = "SELECT ID, FEATURE_CODE, DEVICE_TYPE_ID, CONTENT FROM DM_PROFILE_FEATURES " +
"WHERE PROFILE_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, profileId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
ProfileFeature profileFeature = new ProfileFeature();
Feature feature = new Feature();
feature.setId(resultSet.getInt("FEATURE_ID"));
feature.setCode(resultSet.getString("CODE"));
feature.setName(resultSet.getString("NAME"));
feature.setRuleValue(resultSet.getString("RULE"));
// Feature feature = new Feature();
// feature.setId(resultSet.getInt("FEATURE_ID"));
// feature.setCode(resultSet.getString("CODE"));
// feature.setName(resultSet.getString("NAME"));
// feature.setRuleValue(resultSet.getString("RULE"));
profileFeature.setFeature(feature);
// profileFeature.setFeature(feature);
profileFeature.setId(resultSet.getInt("ID"));
profileFeature.setFeatureCode(resultSet.getString("FEATURE_CODE"));
profileFeature.setDeviceTypeId(resultSet.getInt("DEVICE_TYPE_ID"));
profileFeature.setContent(resultSet.getObject("CONTENT"));
featureList.add(profileFeature);
}

@ -202,7 +202,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_LOCATION (LATITUDE, LONGITUDE, POLICY_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, latitude);
stmt.setString(2, longitude);
stmt.setInt(3, policy.getId());
@ -219,12 +219,196 @@ public class PolicyDAOImpl implements PolicyDAO {
return policy;
}
@Override
public Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys;
int tenantId = PolicyManagerUtil.getTenantId();
try {
conn = this.getConnection();
String query = "INSERT INTO DM_CRITERIA (TENANT_ID, NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
stmt.setString(2, criteria.getName());
stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys();
while (generatedKeys.next()) {
criteria.setId(generatedKeys.getInt(1));
}
} catch (SQLException e) {
String msg = "Error occurred while inserting the criterion (" + criteria.getName() + ") to database.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
return criteria;
}
@Override
public Criterion updateCriterion(Criterion criteria) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PolicyManagerUtil.getTenantId();
try {
conn = this.getConnection();
String query = "UPDATE DM_CRITERIA SET TENANT_ID = ?, NAME = ? WHERE ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
stmt.setString(2, criteria.getName());
stmt.setInt(3, criteria.getId());
stmt.executeUpdate();
} catch (SQLException e) {
String msg = "Error occurred while inserting the criterion (" + criteria.getName() + ") to database.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
return criteria;
}
@Override
public Criterion getCriterion(int id) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Criterion criterion = new Criterion();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_CRITERIA WHERE ID= ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, id);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
criterion.setId(resultSet.getInt("ID"));
criterion.setName(resultSet.getString("NAME"));
}
return criterion;
} catch (SQLException e) {
String msg = "Error occurred while reading the policies from the database.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
public Criterion getCriterion(String name) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Criterion criterion = new Criterion();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_CRITERIA WHERE NAME= ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, name);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
criterion.setId(resultSet.getInt("ID"));
criterion.setName(resultSet.getString("NAME"));
}
return criterion;
} catch (SQLException e) {
String msg = "Error occurred while reading the policies from the database.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
public boolean checkCriterionExists(String name) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
boolean exist = false;
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_CRITERIA WHERE NAME = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, name);
resultSet = stmt.executeQuery();
exist = resultSet.next();
} catch (SQLException e) {
String msg = "Error occurred while checking whether criterion (" + name + ") exists.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
this.closeConnection();
}
return exist;
}
@Override
public boolean deleteCriterion(Criterion criteria) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String query = "DELETE FROM DM_CRITERIA WHERE ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, criteria.getId());
stmt.executeUpdate();
if (log.isDebugEnabled()) {
log.debug("Criterion (" + criteria.getName() + ") delete from database.");
}
return true;
} catch (SQLException e) {
String msg = "Unable to delete the policy (" + criteria.getName() + ") from database.";
log.error(msg);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public List<Criterion> getAllPolicyCriteria() throws PolicyManagerDAOException {
return null;
}
@Override
public Policy addPolicyCriteria(Policy policy) throws PolicyManagerDAOException {
return null;
}
@Override
public List<PolicyCriteria> getPolicyCriteria(int policyId) throws PolicyManagerDAOException {
return null;
}
@Override
public Policy updatePolicy(Policy policy) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET NAME= ?, TENANT_ID = ?, PROFILE_ID = ?, PRIORITY = ? WHERE ID = ?";
@ -241,7 +425,7 @@ public class PolicyDAOImpl implements PolicyDAO {
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
return policy;
}

@ -21,7 +21,13 @@ package org.wso2.carbon.policy.mgt.core.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.policy.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileManagementException;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager;
@ -145,6 +151,28 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
}
}
@Override
public Profile getProfile(int profileId) throws PolicyManagementException {
try {
return profileManager.getProfile(profileId);
} catch (ProfileManagementException e) {
String msg = "Error occurred while retriving profile";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}
}
@Override
public List<Profile> getProfiles() throws PolicyManagementException {
try {
return profileManager.getAllProfiles();
} catch (ProfileManagementException e) {
String msg = "Error occurred while obtaining list of profiles.";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}
}
@Override
public Feature addFeature(Feature feature) throws FeatureManagementException {
try {

@ -26,7 +26,12 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementService;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.PIPDevice;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;

@ -19,7 +19,8 @@
package org.wso2.carbon.policy.mgt.core.mgt;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;

@ -32,7 +32,7 @@ public interface ProfileManager {
boolean deleteProfile(Profile profile) throws ProfileManagementException;
Profile getProfiles(int profileId) throws ProfileManagementException;
Profile getProfile(int profileId) throws ProfileManagementException;
List<Profile> getAllProfiles() throws ProfileManagementException;

@ -20,7 +20,7 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
@ -167,7 +167,7 @@ public class FeatureManagerImpl implements FeatureManager {
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while adding profile feature (" +
feature.getFeature().getName() + " - " + profileId + ")";
feature.getFeatureCode() + " - " + profileId + ")";
log.error(msg, e);
throw new FeatureManagementException(msg, e);
} catch (FeatureManagerDAOException e) {
@ -177,7 +177,7 @@ public class FeatureManagerImpl implements FeatureManager {
log.warn("Unable to roll back the transaction");
}
String msg = "Error occurred while adding profile feature (" +
feature.getFeature().getName() + " - " + profileId + ") to database.";
feature.getFeatureCode() + " - " + profileId + ") to database.";
log.error(msg, e);
throw new FeatureManagementException(msg, e);
}
@ -199,7 +199,7 @@ public class FeatureManagerImpl implements FeatureManager {
log.warn("Unable to roll back the transaction");
}
String msg = "Error occurred while updating feature (" +
feature.getFeature().getName() + " - " + profileId + ")";
feature.getFeatureCode() + " - " + profileId + ")";
log.error(msg, e);
throw new FeatureManagementException(msg, e);
} catch (FeatureManagerDAOException e) {
@ -209,7 +209,7 @@ public class FeatureManagerImpl implements FeatureManager {
log.warn("Unable to roll back the transaction");
}
String msg = "Error occurred while updating feature (" +
feature.getFeature().getName() + " - " + profileId + ") in database.";
feature.getFeatureCode() + " - " + profileId + ") in database.";
log.error(msg, e);
throw new FeatureManagementException(msg, e);
}

@ -26,7 +26,6 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.dao.*;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
@ -70,12 +69,12 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyToUser(policy.getUsers(), policy);
}
if (policy.getRoleList() != null) {
policyDAO.addPolicyToRole(policy.getRoleList(), policy);
if (policy.getRoles() != null) {
policyDAO.addPolicyToRole(policy.getRoles(), policy);
}
if (policy.getDeviceList() != null) {
policyDAO.addPolicyToDevice(policy.getDeviceList(), policy);
if (policy.getDevices() != null) {
policyDAO.addPolicyToDevice(policy.getDevices(), policy);
}
if (policy.getEndDate() != null & policy.getStartDate() != null) {
@ -138,12 +137,12 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyToUser(policy.getUsers(), policy);
}
if (policy.getRoleList() != null) {
policyDAO.addPolicyToRole(policy.getRoleList(), policy);
if (policy.getRoles() != null) {
policyDAO.addPolicyToRole(policy.getRoles(), policy);
}
if (policy.getDeviceList() != null) {
policyDAO.addPolicyToDevice(policy.getDeviceList(), policy);
if (policy.getDevices() != null) {
policyDAO.addPolicyToDevice(policy.getDevices(), policy);
}
if (policy.getEndDate() != null & policy.getStartDate() != null) {
@ -213,16 +212,16 @@ public class PolicyManagerImpl implements PolicyManager {
policy = policyDAO.addPolicyToDevice(deviceList, policy);
PolicyManagementDAOFactory.commitTransaction();
if (policy.getDeviceList() != null) {
if (policy.getDevices() != null) {
if (log.isDebugEnabled()) {
log.debug("Device list of policy is not null.");
}
policy.getDeviceList().addAll(deviceList);
policy.getDevices().addAll(deviceList);
} else {
if (log.isDebugEnabled()) {
log.debug("Device list of policy is null. So added the first device to the list.");
}
policy.setDeviceList(deviceList);
policy.setDevices(deviceList);
}
} catch (PolicyManagerDAOException e) {
@ -260,16 +259,16 @@ public class PolicyManagerImpl implements PolicyManager {
policy = policyDAO.addPolicyToRole(roleNames, policy);
PolicyManagementDAOFactory.commitTransaction();
if (policy.getRoleList() != null) {
if (policy.getRoles() != null) {
if (log.isDebugEnabled()) {
log.debug("New roles list is added to the policy ");
}
policy.getRoleList().addAll(roleNames);
policy.getRoles().addAll(roleNames);
} else {
if (log.isDebugEnabled()) {
log.debug("Roles list was null, new roles are added.");
}
policy.setRoleList(roleNames);
policy.setRoles(roleNames);
}
} catch (PolicyManagerDAOException e) {
@ -298,16 +297,16 @@ public class PolicyManagerImpl implements PolicyManager {
policy = policyDAO.addPolicyToUser(usernameList, policy);
PolicyManagementDAOFactory.commitTransaction();
if (policy.getRoleList() != null) {
if (policy.getRoles() != null) {
if (log.isDebugEnabled()) {
log.debug("New users list is added to the policy ");
}
policy.getRoleList().addAll(usernameList);
policy.getRoles().addAll(usernameList);
} else {
if (log.isDebugEnabled()) {
log.debug("Users list was null, new users list is added.");
}
policy.setRoleList(usernameList);
policy.setRoles(usernameList);
}
} catch (PolicyManagerDAOException e) {
@ -343,8 +342,8 @@ public class PolicyManagerImpl implements PolicyManager {
profile = profileDAO.getProfiles(profileId);
policy.setProfile(profile);
policy.setRoleList(roleNames);
policy.setDeviceList(deviceList);
policy.setRoles(roleNames);
policy.setDevices(deviceList);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while getting the policy related to profile ID (" + profileId + ")";
@ -376,8 +375,8 @@ public class PolicyManagerImpl implements PolicyManager {
Profile profile = profileDAO.getProfiles(policy.getProfile().getProfileId());
policy.setProfile(profile);
policy.setRoleList(roleNames);
policy.setDeviceList(deviceList);
policy.setRoles(roleNames);
policy.setDevices(deviceList);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while getting the policy related to policy ID (" + policyId + ")";
@ -406,8 +405,8 @@ public class PolicyManagerImpl implements PolicyManager {
policy.setProfile(profile);
}
}
policy.setDeviceList(getPolicyAppliedDevicesIds(policy.getId()));
policy.setRoleList(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setDevices(getPolicyAppliedDevicesIds(policy.getId()));
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policyDAO.getDatesOfPolicy(policy);
policyDAO.getTimesOfPolicy(policy);
policyDAO.getLocationsOfPolicy(policy);

@ -178,7 +178,7 @@ public class ProfileManagerImpl implements ProfileManager {
}
@Override
public Profile getProfiles(int profileId) throws ProfileManagementException {
public Profile getProfile(int profileId) throws ProfileManagementException {
Profile profile;
List<ProfileFeature> featureList;
DeviceType deviceType;

@ -19,7 +19,15 @@
package org.wso2.carbon.policy.mgt.core.service;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;

@ -31,7 +31,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
@ -192,7 +192,7 @@ public class PolicyDAOTestCase {
featureList = FeatureCreator.getFeatureList();
//featureManager.addFeatures(featureList);
for (Feature feature : featureList) {
featureManager.addFeature(feature);
// featureManager.addFeature(feature);
}
}

@ -18,7 +18,7 @@
package org.wso2.carbon.policy.mgt.core.util;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import java.util.ArrayList;
import java.util.List;
@ -28,84 +28,95 @@ public class FeatureCreator {
public static List<Feature> getFeatureList() {
Feature feature1 = new Feature();
feature1.setId(1);
feature1.setName("Camera");
feature1.setCode("C001");
feature1.setDescription("Camera");
feature1.setRuleValue("permit_override");
feature1.setDeviceTypeId(1);
// feature1.setRuleValue("permit_override");
feature1.setDeviceType("android");
Feature feature2 = new Feature();
feature2.setId(2);
feature2.setName("LOCK");
feature2.setCode("L001");
feature2.setDescription("Lock the phone");
feature2.setRuleValue("deny_override");
feature2.setDeviceTypeId(1);
// feature2.setRuleValue("deny_override");
feature2.setDeviceType("android");
Feature feature3 = new Feature();
feature3.setId(3);
feature3.setName("WIFI");
feature3.setCode("W001");
feature3.setDescription("Wifi configuration for the device");
feature3.setRuleValue("all_available");
feature3.setDeviceTypeId(1);
// feature3.setRuleValue("all_available");
feature3.setDeviceType("android");
Feature feature4 = new Feature();
feature4.setId(4);
feature4.setName("RING");
feature4.setCode("R001");
feature4.setDescription("Ring the mobile");
feature4.setRuleValue("first_applicable");
feature4.setDeviceTypeId(1);
// feature4.setRuleValue("first_applicable");
feature4.setDeviceType("android");
Feature feature5 = new Feature();
feature5.setId(5);
feature5.setName("LDAP");
feature5.setCode("L002");
feature5.setDescription("LDAP Configurations");
feature5.setRuleValue("all_available");
feature5.setDeviceTypeId(1);
// feature5.setRuleValue("all_available");
feature5.setDeviceType("android");
Feature feature6 = new Feature();
feature6.setId(6);
feature6.setName("VPN");
feature6.setCode("V001");
feature6.setDescription("VPN config for accessing the company network from out side");
feature6.setRuleValue("all_available");
feature6.setDeviceTypeId(1);
// feature6.setRuleValue("all_available");
feature6.setDeviceType("android");
Feature feature7 = new Feature();
feature7.setId(7);
feature7.setName("PASSWORD");
feature7.setCode("P001");
feature7.setDescription("Setting the password for the mobile");
feature7.setRuleValue("first_applicable");
feature7.setDeviceTypeId(1);
// feature7.setRuleValue("first_applicable");
feature7.setDeviceType("android");
Feature feature8 = new Feature();
feature8.setId(8);
feature8.setName("WIPE");
feature8.setCode("W002");
feature8.setDescription("Wiping the company profile created to access the company secure data");
feature8.setRuleValue("permit_override");
feature8.setDeviceTypeId(1);
// feature8.setRuleValue("permit_override");
feature8.setDeviceType("android");
Feature feature9 = new Feature();
feature9.setId(9);
feature9.setName("ENCRYPTION");
feature9.setCode("E001");
feature9.setDescription("Adding the encryption for the phone and SD card.");
feature9.setRuleValue("permit_override");
feature9.setDeviceTypeId(1);
// feature9.setRuleValue("permit_override");
feature9.setDeviceType("android");
Feature feature10 = new Feature();
feature10.setId(10);
feature10.setName("APP");
feature10.setCode("A001");
feature10.setDescription("Installing an application to the phone");
feature10.setRuleValue("permit_override");
feature10.setDeviceTypeId(1);
// feature10.setRuleValue("permit_override");
feature10.setDeviceType("android");
Feature feature11 = new Feature();
feature11.setId(11);
feature11.setName("EMAIL");
feature11.setCode("E002");
feature11.setDescription("Email configurations of the phone.");
feature11.setRuleValue("all_applicable");
feature11.setDeviceTypeId(1);
// feature11.setRuleValue("all_applicable");
feature11.setDeviceType("android");
List<Feature> featureList = new ArrayList<Feature>();

@ -21,9 +21,6 @@ package org.wso2.carbon.policy.mgt.core.util;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.Profile;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@ -49,14 +46,14 @@ public class PolicyCreator {
policy.setPolicyName("New test Policy");
policy.setGeneric(true);
policy.setProfile(profile);
policy.setDeviceList(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType()));
policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType()));
List<String> roles = new ArrayList<String>();
roles.add("Role_01");
roles.add("Role_02");
roles.add("Role_03");
policy.setRoleList(roles);
policy.setRoles(roles);
List<String> users = new ArrayList<String>();
users.add("Geeth");

@ -19,7 +19,7 @@
package org.wso2.carbon.policy.mgt.core.util;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

@ -18,7 +18,7 @@
package org.wso2.carbon.policy.mgt.core.util;
import org.wso2.carbon.policy.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.ArrayList;
@ -33,9 +33,12 @@ public class ProfileFeatureCreator {
ProfileFeature profileFeature = new ProfileFeature();
profileFeature.setContent(feature);
profileFeature.setDeviceTypeId(1);
profileFeature.setFeatureCode(feature.getCode());
// profileFeature.setContent("rrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
// profileFeature.setProfileId(1);
profileFeature.setFeature(feature);
// profileFeature.setFeature(feature);
profileFeatureList.add(profileFeature);
}

@ -131,27 +131,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
;
-- -----------------------------------------------------
-- Table DM_FEATURES
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS DM_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(256) NOT NULL ,
CODE VARCHAR(45) NULL DEFAULT NULL ,
DEVICE_TYPE_ID INT NOT NULL ,
DESCRIPTION TEXT NULL DEFAULT NULL ,
EVALUATION_RULE VARCHAR(60) NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT DM_FEATURES_DEVICE_TYPE
FOREIGN KEY (DEVICE_TYPE_ID )
REFERENCES DM_DEVICE_TYPE (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
;
-- -----------------------------------------------------
-- Table DM_PROFILE_FEATURES
@ -159,19 +138,15 @@ CREATE TABLE IF NOT EXISTS DM_FEATURES (
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT ,
PROFILE_ID INT(11) NOT NULL ,
FEATURE_ID INT(11) NOT NULL ,
CONTENT BLOB NULL DEFAULT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_POLICY_FEATURES_DM_FEATURES
FOREIGN KEY (FEATURE_ID )
REFERENCES DM_FEATURES (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ID INT(11) NOT NULL AUTO_INCREMENT,
PROFILE_ID INT(11) NOT NULL,
FEATURE_CODE VARCHAR(10) NOT NULL,
DEVICE_TYPE_ID INT NOT NULL,
CONTENT BLOB NULL DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES
FOREIGN KEY (PROFILE_ID )
REFERENCES DM_PROFILE (ID )
FOREIGN KEY (PROFILE_ID)
REFERENCES DM_PROFILE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
@ -263,5 +238,28 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
ON DELETE NO ACTION
ON UPDATE NO ACTION)
;
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
ID INT NOT NULL AUTO_INCREMENT ,
DEVICE_ID INT NOT NULL ,
POLICY_ID INT NOT NULL ,
POLICY_CONTENT BLOB NULL ,
APPLIED TINYINT(1) NULL ,
CREATED_TIME TIMESTAMP NULL ,
UPDATED_TIME TIMESTAMP NULL ,
APPLIED_TIME TIMESTAMP NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED
FOREIGN KEY (DEVICE_ID )
REFERENCES DM_DEVICE (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_POLICY_DEVICE_APPLIED_POLICY
FOREIGN KEY (POLICY_ID )
REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
;

@ -57,8 +57,9 @@ public class SimpleEvaluationImpl implements SimpleEvaluation {
sortPolicies();
policy = policyList.get(0);
policyAdministratorPoint = policyManagerService.getPAP();
policyAdministratorPoint.setPolicyUsed(deviceIdentifier, policy);
//TODO : UNCOMMENT THE FOLLOWING CASE
// policyAdministratorPoint = policyManagerService.getPAP();
// policyAdministratorPoint.setPolicyUsed(deviceIdentifier, policy);
}
@ -76,7 +77,7 @@ public class SimpleEvaluationImpl implements SimpleEvaluation {
Collections.sort(policyList);
}
private PolicyManagerService getPolicyManagerService(){
return PolicyDecisionPointDataHolder.getInstance().getPolicyManagerService();
private PolicyManagerService getPolicyManagerService() {
return PolicyDecisionPointDataHolder.getInstance().getPolicyManagerService();
}
}

@ -46,15 +46,16 @@
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Activator>org.wso2.carbon.webapp.authenticator.framework.internal.WebappAuthenticatorFrameworkBundleActivator</Bundle-Activator>
<Require-Bundle>org.wso2.carbon.tomcat.patch</Require-Bundle>
<!--<Require-Bundle>org.wso2.carbon.tomcat.patch</Require-Bundle>-->
<Private-Package>
org.wso2.carbon.webapp.authenticator.framework.internal
</Private-Package>
<DynamicImport-Package>*</DynamicImport-Package>
<Export-Package>
!org.wso2.carbon.webapp.authenticator.framework.internal,
org.wso2.carbon.webapp.authenticator.framework.*
</Export-Package>
<Fragment-Host>tomcat</Fragment-Host>
<!--<Fragment-Host>tomcat</Fragment-Host>-->
</instructions>
</configuration>
</plugin>

@ -0,0 +1,114 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.webapp.authenticator.framework;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
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.w3c.dom.Document;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.core.APIManagerErrorConstants;
import org.wso2.carbon.apimgt.core.authenticate.APITokenValidator;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
public class AuthenticationFrameworkUtil {
private static final Log log = LogFactory.getLog(AuthenticationFrameworkUtil.class);
public static void handleNoMatchAuthScheme(Request request, Response response, String httpVerb, String version,
String context) {
String msg = "Resource is not matched for HTTP Verb: '" + httpVerb + "', API context: '" + context +
"', Version: '" + version + "' and RequestURI: '" + request.getRequestURI() + "'";
handleResponse(request, response, HttpServletResponse.SC_FORBIDDEN, msg);
}
public static boolean doAuthenticate(
String context, String version, String accessToken, String requiredAuthenticationLevel,
String clientDomain) throws APIManagementException, AuthenticationException {
if (APIConstants.AUTH_NO_AUTHENTICATION.equals(requiredAuthenticationLevel)) {
return true;
}
APITokenValidator tokenValidator = new APITokenValidator();
APIKeyValidationInfoDTO apiKeyValidationDTO = tokenValidator.validateKey(context, version, accessToken,
requiredAuthenticationLevel, clientDomain);
if (apiKeyValidationDTO.isAuthorized()) {
String userName = apiKeyValidationDTO.getEndUserName();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
try {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(
IdentityUtil.getTenantIdOFUser(userName));
} catch (IdentityException e) {
throw new AuthenticationException("Error occurred while retrieving the tenant ID of user '" +
userName + "'", e);
}
} else {
throw new AuthenticationException(apiKeyValidationDTO.getValidationStatus(),
"Access failure for API: " + context + ", version: " +
version + " with key: " + accessToken);
}
return false;
}
public static void handleResponse(Request request, Response response, int statusCode, String payload) {
response.setStatus(statusCode);
String targetResponseContentType =
request.getHeader(Constants.HTTPHeaders.HEADER_HTTP_ACCEPT);
if (targetResponseContentType != null && !"".equals(targetResponseContentType) &&
!Constants.ContentTypes.CONTENT_TYPE_ANY.equals(targetResponseContentType)) {
response.setContentType(targetResponseContentType);
} else {
response.setContentType(Constants.ContentTypes.CONTENT_TYPE_APPLICATION_XML);
}
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(payload);
} catch (IOException e) {
log.error("Error occurred while sending faulty response back to the client", e);
}
}
public static Document convertToDocument(File file) throws AuthenticatorFrameworkException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new AuthenticatorFrameworkException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
}

@ -0,0 +1,74 @@
/*
* 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 AuthenticatorFrameworkException extends Exception {
private static final long serialVersionUID = -3151279311229070297L;
private String errorMessage;
private int errorCode;
public AuthenticatorFrameworkException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public AuthenticatorFrameworkException(int errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public AuthenticatorFrameworkException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public AuthenticatorFrameworkException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public AuthenticatorFrameworkException(String msg) {
super(msg);
setErrorMessage(msg);
}
public AuthenticatorFrameworkException() {
super();
}
public AuthenticatorFrameworkException(Throwable cause) {
super(cause);
}
}

@ -1,50 +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.connector.Request;
public class BasicAuthAuthenticator implements WebappAuthenticator {
private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuthAuthenticator";
private String username;
private String password;
public BasicAuthAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public boolean isAuthenticated(Request request) {
return false;
}
@Override
public Status authenticate(Request request) {
return Status.CONTINUE;
}
@Override
public String getAuthenticatorName() {
return BasicAuthAuthenticator.BASIC_AUTH_AUTHENTICATOR;
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.webapp.authenticator.framework;
public final class Constants {
public static final String AUTHORIZATION_HEADER_PREFIX_BEARER = "Bearer";
public static final String NO_MATCHING_AUTH_SCHEME = "noMatchedAuthScheme";
public static final class HTTPHeaders {
private HTTPHeaders() {
throw new AssertionError();
}
public static final String HEADER_HTTP_ACCEPT = "Accept";
public static final String HEADER_HTTP_AUTHORIZATION = "Authorization";
}
public static final class ContentTypes {
private ContentTypes() {
throw new AssertionError();
}
public static final String CONTENT_TYPE_ANY = "*/*";
public static final String CONTENT_TYPE_APPLICATION_XML = "application/xml";
}
}

@ -1,140 +0,0 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.webapp.authenticator.framework;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.catalina.connector.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.core.APIManagerErrorConstants;
import org.wso2.carbon.apimgt.core.authenticate.APITokenValidator;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class HandlerUtil {
private static final Log log = LogFactory.getLog(HandlerUtil.class);
/**
* Retrieve bearer token form the HTTP header
* @param bearerToken Bearer Token extracted out of the corresponding HTTP header
*/
public static String getAccessToken(String bearerToken) {
String accessToken = null;
String[] token = bearerToken.split(HandlerConstants.TOKEN_NAME_BEARER);
if (token.length > 1 && token[1] != null) {
accessToken = token[1].trim();
}
return accessToken;
}
public static String getAPIVersion(HttpServletRequest request) {
int contextStartsIndex = (request.getRequestURI()).indexOf(request.getContextPath()) + 1;
int length = request.getContextPath().length();
String afterContext = (request.getRequestURI()).substring(contextStartsIndex + length);
int SlashIndex = afterContext.indexOf(("/"));
if (SlashIndex != -1) {
return afterContext.substring(0, SlashIndex);
} else {
return afterContext;
}
}
public static void handleNoMatchAuthSchemeCallForRestService(Response response,String httpVerb, String reqUri,
String version, String context ) {
String errMsg = "Resource is not matched for HTTP Verb " + httpVerb + ". API context " + context +
",version " + version + ", request " + reqUri;
AuthenticationException e =
new AuthenticationException(APIManagerErrorConstants.API_AUTH_INCORRECT_API_RESOURCE, errMsg);
String faultPayload = getFaultPayload(e, APIManagerErrorConstants.API_SECURITY_NS,
APIManagerErrorConstants.API_SECURITY_NS_PREFIX).toString();
handleRestFailure(response, faultPayload);
}
public static boolean doAuthenticate(String context, String version, String accessToken,
String requiredAuthenticationLevel, String clientDomain)
throws APIManagementException,
AuthenticationException {
if (APIConstants.AUTH_NO_AUTHENTICATION.equals(requiredAuthenticationLevel)) {
return true;
}
APITokenValidator tokenValidator = new APITokenValidator();
APIKeyValidationInfoDTO apiKeyValidationDTO = tokenValidator.validateKey(context, version, accessToken,
requiredAuthenticationLevel, clientDomain);
if (apiKeyValidationDTO.isAuthorized()) {
String userName = apiKeyValidationDTO.getEndUserName();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setUsername(apiKeyValidationDTO.getEndUserName());
try {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantId(IdentityUtil.getTenantIdOFUser(userName));
} catch (IdentityException e) {
log.error("Error while retrieving Tenant Id", e);
return false;
}
return true;
} else {
throw new AuthenticationException(apiKeyValidationDTO.getValidationStatus(),
"Access failure for API: " + context + ", version: " +
version + " with key: " + accessToken);
}
}
public static void handleRestFailure(Response response, String payload) {
response.setStatus(403);
response.setContentType("application/xml");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(payload);
} catch (IOException e) {
log.error("Error in sending fault response", e);
}
}
public static OMElement getFaultPayload(AuthenticationException exception, String FaultNS,
String FaultNSPrefix) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace(FaultNS, FaultNSPrefix);
OMElement payload = fac.createOMElement("fault", ns);
OMElement errorCode = fac.createOMElement("code", ns);
errorCode.setText(String.valueOf(exception.getErrorCode()));
OMElement errorMessage = fac.createOMElement("message", ns);
errorMessage.setText(APIManagerErrorConstants.getFailureMessage(exception.getErrorCode()));
OMElement errorDetail = fac.createOMElement("description", ns);
errorDetail.setText(exception.getMessage());
payload.addChild(errorCode);
payload.addChild(errorMessage);
payload.addChild(errorDetail);
return payload;
}
}

@ -19,6 +19,7 @@
package org.wso2.carbon.webapp.authenticator.framework;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
public interface WebappAuthenticator {
@ -28,7 +29,7 @@ public interface WebappAuthenticator {
boolean isAuthenticated(Request request);
Status authenticate(Request request);
Status authenticate(Request request, Response response);
String getAuthenticatorName();

@ -23,45 +23,13 @@ import org.apache.catalina.util.Base64;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator;
public class WebappAuthenticatorFactory {
public static WebappAuthenticator getAuthenticator(Request request) {
MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
if (authorization != null) {
authorization.toBytes();
ByteChunk authBC = authorization.getByteChunk();
if (authBC.startsWithIgnoreCase("basic ", 0)) {
authBC.setOffset(authBC.getOffset() + 6);
CharChunk authCC = authorization.getCharChunk();
Base64.decode(authBC, authCC);
String username;
String password = null;
int colon = authCC.indexOf(':');
if (colon < 0) {
username = authCC.toString();
} else {
char[] buf = authCC.getBuffer();
username = new String(buf, 0, colon);
password = new String(buf, colon + 1, authCC.getEnd() - colon - 1);
}
authBC.setOffset(authBC.getOffset() - 6);
return new BasicAuthAuthenticator(username, password);
} else if (authBC.startsWithIgnoreCase("bearer ", 0)) {
authBC.setOffset(authBC.getOffset() + 7);
CharChunk authCC = authorization.getCharChunk();
char[] buf = authCC.getBuffer();
String bearer = new String(buf, 0, authCC.getEnd() - 1);
authBC.setOffset(authBC.getOffset() - 7);
return new OAuthAuthenticator(bearer);
}
}
throw new IllegalArgumentException("Failed to determine an appropriate authenticator to be used, based " +
"on the incoming request");
return new OAuthAuthenticator();
}
}

@ -18,29 +18,37 @@
*/
package org.wso2.carbon.webapp.authenticator.framework;
import org.apache.axis2.context.MessageContext;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator;
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 javax.servlet.ServletException;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class WebappAuthenticatorFrameworkValve extends CarbonTomcatValve {
private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkValve.class);
@Override
public void invoke(Request request, Response response, CompositeValve compositeValve) {
WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request);
WebappAuthenticator.Status status = authenticator.authenticate(request);
WebappAuthenticator.Status status = authenticator.authenticate(request, response);
this.processResponse(request, response, compositeValve, status);
}
private void processResponse(Request request, Response response, CompositeValve compositeValve,
WebappAuthenticator.Status status) {
switch (status) {
case SUCCESS:
case CONTINUE:
getNext().invoke(request, response, compositeValve);
this.getNext().invoke(request, response, compositeValve);
case FAILURE:
//do something
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED,
"Failed to authorize the incoming request");
}
}
}

@ -0,0 +1,96 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.webapp.authenticator.framework.authenticator;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
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;
public class BasicAuthAuthenticator implements WebappAuthenticator {
private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuthAuthenticator";
@Override
public boolean isAuthenticated(Request request) {
return false;
}
@Override
public Status authenticate(Request request, Response response) {
return Status.CONTINUE;
}
@Override
public String getAuthenticatorName() {
return BasicAuthAuthenticator.BASIC_AUTH_AUTHENTICATOR;
}
private Credentials getCredentials(Request request) {
Credentials credentials = null;
MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
if (authorization != null) {
authorization.toBytes();
ByteChunk authBC = authorization.getByteChunk();
if (authBC.startsWithIgnoreCase("basic ", 0)) {
authBC.setOffset(authBC.getOffset() + 6);
CharChunk authCC = authorization.getCharChunk();
Base64.decode(authBC, authCC);
String username;
String password = null;
int colon = authCC.indexOf(':');
if (colon < 0) {
username = authCC.toString();
} else {
char[] buf = authCC.getBuffer();
username = new String(buf, 0, colon);
password = new String(buf, colon + 1, authCC.getEnd() - colon - 1);
}
authBC.setOffset(authBC.getOffset() - 6);
credentials = new Credentials(username, password);
}
}
return credentials;
}
public static class Credentials {
private String username;
private String password;
public Credentials(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
}

@ -16,81 +16,80 @@
* 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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.core.authenticate.APITokenValidator;
import org.wso2.carbon.apimgt.core.gateway.APITokenAuthenticator;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
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;
public class OAuthAuthenticator implements WebappAuthenticator {
private static final String OAUTH_AUTHENTICATOR = "OAuthAuthenticator";
private static APITokenAuthenticator authenticator = new APITokenAuthenticator();
private String bearerToken;
private static final Log log = LogFactory.getLog(OAuthAuthenticator.class);
public OAuthAuthenticator(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public boolean isAuthenticated(Request request) {
return false;
}
@Override
public Status authenticate(Request request) {
public Status authenticate(Request request, Response response) {
StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/");
String context = request.getContextPath();
if (context == null || "".equals(context)) {
return Status.CONTINUE;
context = tokenizer.nextToken();
if (context == null || "".equals(context)) {
return Status.CONTINUE;
}
}
boolean contextExist;
Boolean contextValueInCache = null;
boolean isContextCached = false;
if (APIUtil.getAPIContextCache().get(context) != null) {
contextValueInCache = Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
}
if (contextValueInCache != null) {
contextExist = contextValueInCache;
} else {
contextExist = ApiMgtDAO.isContextExist(context);
APIUtil.getAPIContextCache().put(context, contextExist);
isContextCached = Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
}
if (!contextExist) {
if (!isContextCached) {
return Status.CONTINUE;
}
try {
String apiVersion = HandlerUtil.getAPIVersion(request);
String apiVersion = tokenizer.nextToken();
String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
String authLevel = authenticator.getResourceAuthenticationScheme(context,
apiVersion,
request.getRequestURI(),
request.getMethod());
if (HandlerConstants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) {
HandlerUtil.handleNoMatchAuthSchemeCallForRestService(null,
request.getMethod(), request.getRequestURI(),
String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion,
request.getRequestURI(), request.getMethod());
if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) {
AuthenticationFrameworkUtil.handleNoMatchAuthScheme(request, response, request.getMethod(),
apiVersion, context);
return Status.CONTINUE;
} else {
String bearerToken = this.getBearerToken(request);
boolean isAuthenticated =
HandlerUtil.doAuthenticate(context, apiVersion, bearerToken, authLevel, domain);
AuthenticationFrameworkUtil.doAuthenticate(context, apiVersion, bearerToken, authLevel, domain);
return (isAuthenticated) ? Status.SUCCESS : Status.FAILURE;
}
} catch (APIManagementException e) {
//ignore
} catch (AuthenticationException e) {
log.error("Error occurred while key validation", e);
return Status.FAILURE;
} catch (AuthenticationException e) {
log.error("Failed to authenticate the incoming request", e);
return Status.FAILURE;
}
return Status.CONTINUE;
}
@Override
@ -98,5 +97,19 @@ public class OAuthAuthenticator implements WebappAuthenticator {
return OAuthAuthenticator.OAUTH_AUTHENTICATOR;
}
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();
if (authBC.startsWithIgnoreCase("bearer ", 0)) {
String bearerToken = authBC.toString();
tokenValue = bearerToken.substring(8, bearerToken.length() - 1);
}
}
return tokenValue;
}
}

@ -0,0 +1,48 @@
/*
* 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.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Authenticator")
public class AuthenticatorConfig {
private String name;
private String className;
@XmlElement(name = "Name", required = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name = "ClassName", required = true)
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}

@ -0,0 +1,74 @@
/*
* 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.config;
public class InvalidConfigurationStateException extends RuntimeException {
private static final long serialVersionUID = -3151279311229070297L;
private String errorMessage;
private int errorCode;
public InvalidConfigurationStateException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public InvalidConfigurationStateException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public InvalidConfigurationStateException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public InvalidConfigurationStateException(String msg) {
super(msg);
setErrorMessage(msg);
}
public InvalidConfigurationStateException() {
super();
}
public InvalidConfigurationStateException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,102 @@
/*
* 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.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkException;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.util.List;
@XmlRootElement(name = "WebappAuthenticatorConfig")
public class WebappAuthenticatorConfig {
private List<AuthenticatorConfig> authenticators;
private static WebappAuthenticatorConfig config;
private static final Log log = LogFactory.getLog(WebappAuthenticatorConfig.class);
private static final String AUTHENTICATOR_CONFIG_PATH =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "webapp-authenticator-config.xml";
private static final String AUTHENTICATOR_CONFIG_SCHEMA_PATH =
"resources/config/schema/webapp-authenticator-config-schema.xsd";
private WebappAuthenticatorConfig() {
}
public static WebappAuthenticatorConfig getInstance() {
if (config == null) {
throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " +
"initialized properly");
}
return config;
}
@XmlElementWrapper(name = "Authenticators", required = true)
@XmlElement(name = "Authenticator", required = true)
public List<AuthenticatorConfig> getAuthenticators() {
return authenticators;
}
@SuppressWarnings("unused")
public void setAuthenticators(List<AuthenticatorConfig> authenticators) {
this.authenticators = authenticators;
}
public static void init() throws AuthenticatorFrameworkException {
try {
File authConfig = new File(WebappAuthenticatorConfig.AUTHENTICATOR_CONFIG_PATH);
Document doc = AuthenticationFrameworkUtil.convertToDocument(authConfig);
/* Un-marshaling Webapp Authenticator configuration */
JAXBContext ctx = JAXBContext.newInstance(WebappAuthenticatorConfig.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
//unmarshaller.setSchema(getSchema());
config = (WebappAuthenticatorConfig) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new AuthenticatorFrameworkException("Error occurred while un-marshalling Webapp Authenticator " +
"Framework Config", e);
}
}
private static Schema getSchema() throws AuthenticatorFrameworkException {
try {
File deviceManagementSchemaConfig = new File(WebappAuthenticatorConfig.AUTHENTICATOR_CONFIG_SCHEMA_PATH);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
return factory.newSchema(deviceManagementSchemaConfig);
} catch (SAXException e) {
throw new AuthenticatorFrameworkException("Error occurred while initializing the schema of " +
"webapp-authenticator-config.xml", e);
}
}
}

@ -25,6 +25,7 @@ import org.osgi.framework.BundleContext;
import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorFrameworkValve;
import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig;
import java.util.ArrayList;
import java.util.List;
@ -39,6 +40,7 @@ public class WebappAuthenticatorFrameworkBundleActivator implements BundleActiva
log.debug("Starting Web Application Authenticator Framework Bundle");
}
try {
WebappAuthenticatorConfig.init();
List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>();
valves.add(new WebappAuthenticatorFrameworkValve());
TomcatValveContainer.addValves(valves);
@ -47,7 +49,7 @@ public class WebappAuthenticatorFrameworkBundleActivator implements BundleActiva
log.debug("Web Application Authenticator Framework Bundle has been started successfully");
}
} catch (Throwable e) {
log.error("Error occurred while initializing the bundle");
log.error("Error occurred while initializing the bundle", e);
}
}

@ -19,27 +19,27 @@
<APIPublisherConfig>
<APIs>
<API>
<Name>appmanager</Name>
<Name>AppManagerController</Name>
<Owner>admin</Owner>
<Context>devices</Context>
<Context>appmanager</Context>
<Version>1.0.0</Version>
<Endpoint>http://localhost:9763/</Endpoint>
<Endpoint>http://localhost:9763/appmanager</Endpoint>
<Transports>http,https</Transports>
</API>
<API>
<Name>enrollment</Name>
<Owner>admin</Owner>
<Context>enroll</Context>
<Context>enrollment</Context>
<Version>1.0.0</Version>
<Endpoint>http://localhost:9763/cdm-android-api/enrollment/</Endpoint>
<Endpoint>http://localhost:9763/enrollment</Endpoint>
<Transports>http,https</Transports>
</API>
<API>
<Name>license</Name>
<Owner>admin</Owner>
<Context>license</Context>
<Context>license-mgt</Context>
<Version>1.0.0</Version>
<Endpoint>http://localhost:9763/cdm-android-api/devices/license</Endpoint>
<Endpoint>http://localhost:9763/license-mgt</Endpoint>
<Transports>http,https</Transports>
</API>
<API>
@ -47,7 +47,7 @@
<Owner>admin</Owner>
<Context>operation</Context>
<Version>1.0.0</Version>
<Endpoint>http://localhost:9763/cdm-android-ap/operations/</Endpoint>
<Endpoint>http://localhost:9763/operations</Endpoint>
<Transports>http,https</Transports>
</API>
</APIs>

@ -66,6 +66,132 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_MAPPING (
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
--- POLICY RELATED TABLES ----
CREATE TABLE IF NOT EXISTS DM_PROFILE (
ID INT NOT NULL AUTO_INCREMENT ,
PROFILE_NAME VARCHAR(45) NOT NULL ,
TENANT_ID INT NOT NULL ,
DEVICE_TYPE_ID INT NOT NULL ,
CREATED_TIME DATETIME NOT NULL ,
UPDATED_TIME DATETIME NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT DM_PROFILE_DEVICE_TYPE FOREIGN KEY (DEVICE_TYPE_ID ) REFERENCES DM_DEVICE_TYPE (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) NULL DEFAULT NULL ,
TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL ,
PRIORITY INT NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) REFERENCES DM_PROFILE (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT ,
DEVICE_ID INT(11) NOT NULL ,
POLICY_ID INT(11) NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DEVICE_DEVICE_POLICY FOREIGN KEY (DEVICE_ID ) REFERENCES DM_DEVICE (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
ID INT(11) NOT NULL ,
DEVICE_TYPE_ID INT(11) NOT NULL ,
POLICY_ID INT(11) NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE FOREIGN KEY (DEVICE_TYPE_ID ) REFERENCES DM_DEVICE_TYPE (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT,
PROFILE_ID INT(11) NOT NULL,
FEATURE_CODE VARCHAR(10) NOT NULL,
DEVICE_TYPE_ID INT NOT NULL,
CONTENT BLOB NULL DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES FOREIGN KEY (PROFILE_ID) REFERENCES DM_PROFILE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT ,
ROLE_NAME VARCHAR(45) NOT NULL ,
POLICY_ID INT(11) NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_LOCATION (
LATITUDE VARCHAR(45) NOT NULL ,
LONGITUDE VARCHAR(45) NOT NULL ,
POLICY_ID INT(11) NOT NULL ,
CONSTRAINT FK_DM_POLICY_DM_LOCATION FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_TIME (
STARTING_TIME DATETIME NOT NULL ,
ENDING_TIME DATETIME NOT NULL ,
POLICY_ID INT(11) NOT NULL ,
CONSTRAINT FK_DM_POLICY_DM_TIME FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_DATE (
START_DATE DATE NOT NULL ,
END_DATE DATE NOT NULL ,
POLICY_ID INT NOT NULL ,
CONSTRAINT DM_DATE_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
ID INT NOT NULL AUTO_INCREMENT ,
POLICY_ID INT NOT NULL ,
USERNAME VARCHAR(45) NOT NULL ,
PRIMARY KEY (ID) ,
CONSTRAINT DM_POLICY_USER_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
-- POLICY RELATED TABLES FINISHED --
-- TO:DO - Remove this INSERT sql statement.
Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android');
Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (2, 'ios');
--Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android');
--Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (2, 'ios');

Loading…
Cancel
Save