You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ranger.apache.org by ma...@apache.org on 2014/12/12 02:29:48 UTC
[05/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/SearchField.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/SearchField.java b/security-admin/src/main/java/org/apache/ranger/common/SearchField.java
new file mode 100644
index 0000000..b232559
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/SearchField.java
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+public class SearchField {
+ public enum DATA_TYPE {
+ INTEGER, STRING, INT_LIST, STR_LIST, BOOLEAN, DATE
+ };
+
+ public enum SEARCH_TYPE {
+ FULL, PARTIAL, LESS_THAN, LESS_EQUAL_THAN, GREATER_THAN, GREATER_EQUAL_THAN
+ };
+
+ private String clientFieldName;
+ private String fieldName;
+ private DATA_TYPE dataType;
+ private SEARCH_TYPE searchType;
+ private String regEx;
+ private String enumName;
+ private int maxValue;
+ private List<String> joinTables;
+ private String joinCriteria;
+ private String customCondition;
+
+ /**
+ * default constructor
+ */
+ public SearchField(String clientFieldName, String fieldName,
+ DATA_TYPE dtype, SEARCH_TYPE stype, String joinTables,
+ String joinCriteria) {
+ this.clientFieldName = clientFieldName;
+ this.fieldName = fieldName;
+ dataType = dtype;
+ searchType = stype;
+
+ setJoinTables(joinTables);
+ this.joinCriteria = joinCriteria;
+ }
+
+ /**
+ * constructor
+ */
+ public SearchField(String clientFieldName, String fieldName,
+ DATA_TYPE dtype, SEARCH_TYPE stype) {
+ this.clientFieldName = clientFieldName;
+ this.fieldName = fieldName;
+ dataType = dtype;
+ searchType = stype;
+ }
+
+ /**
+ * constructor
+ */
+ public SearchField(String clientFieldName, String fieldName) {
+ this.clientFieldName = clientFieldName;
+ this.fieldName = fieldName;
+ dataType = DATA_TYPE.STRING;
+ searchType = SEARCH_TYPE.FULL;
+ }
+
+ static public SearchField createString(String clientFieldName,
+ String fieldName, SEARCH_TYPE stype, String regEx) {
+ SearchField searchField = new SearchField(clientFieldName, fieldName,
+ DATA_TYPE.STRING, stype);
+ searchField.setRegEx(regEx);
+ return searchField;
+ }
+
+ static public SearchField createLong(String clientFieldName,
+ String fieldName) {
+ SearchField searchField = new SearchField(clientFieldName, fieldName,
+ DATA_TYPE.INTEGER, SEARCH_TYPE.FULL);
+ return searchField;
+ }
+
+ static public SearchField createEnum(String clientFieldName,
+ String fieldName, String enumName, int maxValue) {
+ SearchField searchField = new SearchField(clientFieldName, fieldName,
+ DATA_TYPE.INT_LIST, SEARCH_TYPE.FULL);
+ searchField.setEnumName(enumName);
+ searchField.setMaxValue(maxValue);
+ return searchField;
+ }
+
+ public String getClientFieldName() {
+ return clientFieldName;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public void setFieldName(String fieldName) {
+ this.fieldName = fieldName;
+ }
+
+ public DATA_TYPE getDataType() {
+ return dataType;
+ }
+
+ public void setDataType(DATA_TYPE dataType) {
+ this.dataType = dataType;
+ }
+
+ public SEARCH_TYPE getSearchType() {
+ return searchType;
+ }
+
+ /**
+ * @param regEx
+ * the regEx to set
+ */
+ public void setRegEx(String regEx) {
+ this.regEx = regEx;
+ }
+
+ /**
+ * @param enumName
+ * the enumName to set
+ */
+ public void setEnumName(String enumName) {
+ this.enumName = enumName;
+ }
+
+ /**
+ * @param maxValue
+ * the maxValue to set
+ */
+ public void setMaxValue(int maxValue) {
+ this.maxValue = maxValue;
+ }
+
+ /**
+ * @return the joinTables
+ */
+ public List<String> getJoinTables() {
+ return joinTables;
+ }
+
+ /**
+ * @param joinTables
+ * the joinTables to set
+ */
+ public void setJoinTables(List<String> joinTables) {
+ this.joinTables = joinTables;
+ }
+
+ /**
+ * @param joinTables
+ * the joinTables to set (comma separated)
+ */
+ public void setJoinTables(String joinTables) {
+ if (joinTables != null) {
+ if (this.joinTables == null) {
+ this.joinTables = new ArrayList<String>();
+ }
+
+ for (String table : joinTables.split(",")) {
+ if (table == null) {
+ continue;
+ }
+ table = table.trim();
+
+ if (!table.isEmpty() && !this.joinTables.contains(table)) {
+ this.joinTables.add(table);
+ }
+ }
+
+ }
+ }
+
+ /**
+ * @return the joinCriteria
+ */
+ public String getJoinCriteria() {
+ return joinCriteria;
+ }
+
+ /**
+ * @param joinCriteria
+ * the joinCriteria to set
+ */
+ public void setJoinCriteria(String joinCriteria) {
+ this.joinCriteria = joinCriteria;
+ }
+
+ /**
+ * @return the customCondition
+ */
+ public String getCustomCondition() {
+ return customCondition;
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/SearchGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/SearchGroup.java b/security-admin/src/main/java/org/apache/ranger/common/SearchGroup.java
new file mode 100644
index 0000000..fce2801
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/SearchGroup.java
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.Query;
+
+public class SearchGroup {
+ public enum CONDITION {
+ AND, OR
+ }
+
+ CONDITION condition = CONDITION.AND;
+
+ List<SearchValue> values = new ArrayList<SearchValue>();
+ List<SearchGroup> searchGroups = new ArrayList<SearchGroup>();
+
+ /**
+ * @param condition
+ */
+ public SearchGroup(CONDITION condition) {
+ this.condition = condition;
+ }
+
+ public String getWhereClause(String prefix) {
+ if ((values == null || values.size() == 0)
+ && (searchGroups == null || searchGroups.size() == 0)) {
+ return "";
+ }
+ int count = -1;
+ int innerCount = 0;
+ StringBuilder whereClause = new StringBuilder("(");
+ for (SearchValue value : values) {
+ count++;
+ if (count > 0) {
+ if (condition.equals(CONDITION.AND)) {
+ whereClause.append(" AND ");
+ } else {
+ whereClause.append(" OR ");
+ }
+ }
+ SearchField searchField = value.getSearchField();
+ if (value.isList()) {
+ whereClause.append(" (");
+ int listCount = value.getValueList().size();
+ for (int i = 0; i < listCount; i++) {
+ if (i > 0) {
+ whereClause.append(" OR ");
+ }
+ whereClause
+ .append(searchField.getFieldName())
+ .append(" = :")
+ .append(searchField.getClientFieldName() + "_"
+ + prefix + "_" + count + "_" + innerCount);
+ innerCount++;
+ }
+ whereClause.append(") ");
+ } else {
+ whereClause
+ .append(searchField.getFieldName())
+ .append(" = :")
+ .append(searchField.getClientFieldName() + "_" + prefix
+ + "_" + count);
+ }
+ }
+
+ for (SearchGroup searchGroup : searchGroups) {
+ count++;
+ if (count > 0) {
+ if (condition.equals(CONDITION.AND)) {
+ whereClause.append(" AND ");
+ } else {
+ whereClause.append(" OR ");
+ }
+ }
+ whereClause.append(" ")
+ .append(searchGroup.getWhereClause(prefix + "_" + count))
+ .append(" ");
+ }
+ whereClause.append(") ");
+ return whereClause.toString();
+ }
+
+ /**
+ * @param query
+ */
+ public void resolveValues(Query query, String prefix) {
+ if ((values == null || values.size() == 0)
+ && (searchGroups == null || searchGroups.size() == 0)) {
+ return;
+ }
+
+ int count = -1;
+ int innerCount = 0;
+ for (SearchValue value : values) {
+ count++;
+ SearchField searchField = value.getSearchField();
+ if (value.isList()) {
+ int listCount = value.getValueList().size();
+ for (int i = 0; i < listCount; i++) {
+ String paramName = searchField.getClientFieldName() + "_"
+ + prefix + "_" + count + "_" + innerCount;
+ query.setParameter(paramName, value.getValueList().get(i));
+ innerCount++;
+ }
+ } else {
+ String paramName = searchField.getClientFieldName() + "_"
+ + prefix + "_" + count;
+ query.setParameter(paramName, value.getValue());
+ }
+ }
+
+ for (SearchGroup searchGroup : searchGroups) {
+ count++;
+ searchGroup.resolveValues(query, prefix + "_" + count);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/SearchUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/SearchUtil.java b/security-admin/src/main/java/org/apache/ranger/common/SearchUtil.java
new file mode 100644
index 0000000..d1782ce
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/SearchUtil.java
@@ -0,0 +1,819 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Query;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+
+@Component
+public class SearchUtil {
+ final static Logger logger = Logger.getLogger(SearchUtil.class);
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XAConfigUtil configUtil;
+
+ // @Autowired
+ // AKADomainObjectSecurityHandler securityHandler;
+
+ @Autowired
+ StringUtil stringUtil;
+
+ int minInListLength = 20;
+ String defaultDateFormat="MM/dd/yyyy";
+
+ public SearchUtil() {
+ minInListLength = PropertiesUtil.getIntProperty(
+ "xa.db.min_inlist", minInListLength);
+ defaultDateFormat = PropertiesUtil.getProperty(
+ "xa.ui.defaultDateformat", defaultDateFormat);
+
+ }
+
+ @Deprecated
+ public SearchCriteria extractCommonCriterias(HttpServletRequest request,
+ String[] approvedSortByParams) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+
+ int startIndex = restErrorUtil.parseInt(
+ request.getParameter("startIndex"), 0,
+ "Invalid value for parameter startIndex",
+ MessageEnums.INVALID_INPUT_DATA, null, "startIndex");
+ searchCriteria.setStartIndex(startIndex);
+
+ int pageSize = restErrorUtil.parseInt(request.getParameter("pageSize"),
+ configUtil.getDefaultMaxRows(),
+ "Invalid value for parameter pageSize",
+ MessageEnums.INVALID_INPUT_DATA, null, "pageSize");
+ searchCriteria.setMaxRows(pageSize);
+
+ String sortBy = restErrorUtil.validateString(
+ request.getParameter("sortBy"), StringUtil.VALIDATION_ALPHA,
+ "Invalid value for parameter sortBy",
+ MessageEnums.INVALID_INPUT_DATA, null, "sortBy");
+
+ boolean sortSet = false;
+ for (int i = 0; approvedSortByParams != null
+ && i < approvedSortByParams.length; i++) {
+
+ if (approvedSortByParams[i].equalsIgnoreCase(sortBy)) {
+ searchCriteria.setSortBy(approvedSortByParams[i]);
+ String sortType = restErrorUtil.validateString(
+ request.getParameter("sortType"),
+ StringUtil.VALIDATION_ALPHA,
+ "Invalid value for parameter sortType",
+ MessageEnums.INVALID_INPUT_DATA, null, "sortType");
+ searchCriteria.setSortType(sortType);
+ sortSet = true;
+ break;
+ }
+ }
+ if (!sortSet && !stringUtil.isEmpty(sortBy)) {
+ logger.info("Invalid or unsupported sortBy field passed. sortBy="
+ + sortBy, new Throwable());
+ }
+
+ return searchCriteria;
+ }
+
+ /**
+ * @param request
+ * @param sortFields
+ * @return
+ */
+ public SearchCriteria extractCommonCriterias(HttpServletRequest request,
+ List<SortField> sortFields) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+
+ int startIndex = restErrorUtil.parseInt(
+ request.getParameter("startIndex"), 0,
+ "Invalid value for parameter startIndex",
+ MessageEnums.INVALID_INPUT_DATA, null, "startIndex");
+ searchCriteria.setStartIndex(startIndex);
+
+ int pageSize = restErrorUtil.parseInt(request.getParameter("pageSize"),
+ configUtil.getDefaultMaxRows(),
+ "Invalid value for parameter pageSize",
+ MessageEnums.INVALID_INPUT_DATA, null, "pageSize");
+ searchCriteria.setMaxRows(pageSize);
+
+ // is count needed
+ searchCriteria.setGetCount(restErrorUtil.parseBoolean(
+ request.getParameter("getCount"), true));
+
+ searchCriteria.setOwnerId(restErrorUtil.parseLong(
+ request.getParameter("ownerId"), null));
+ searchCriteria.setGetChildren(restErrorUtil.parseBoolean(
+ request.getParameter("getChildren"), false));
+
+ String sortBy = restErrorUtil.validateString(
+ request.getParameter("sortBy"), StringUtil.VALIDATION_ALPHA,
+ "Invalid value for parameter sortBy",
+ MessageEnums.INVALID_INPUT_DATA, null, "sortBy");
+
+ boolean sortSet = false;
+ if (!stringUtil.isEmpty(sortBy)) {
+ for (SortField sortField : sortFields) {
+ if (sortField.getParamName().equalsIgnoreCase(sortBy)) {
+ searchCriteria.setSortBy(sortField.getParamName());
+ String sortType = restErrorUtil.validateString(
+ request.getParameter("sortType"),
+ StringUtil.VALIDATION_ALPHA,
+ "Invalid value for parameter sortType",
+ MessageEnums.INVALID_INPUT_DATA, null, "sortType");
+ searchCriteria.setSortType(sortType);
+ sortSet = true;
+ break;
+ }
+ }
+ }
+
+ if (!sortSet && !stringUtil.isEmpty(sortBy)) {
+ logger.info("Invalid or unsupported sortBy field passed. sortBy="
+ + sortBy, new Throwable());
+ }
+
+ return searchCriteria;
+ }
+
+
+
+ public Long extractLong(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName) {
+ String[] values = getParamMultiValues(request, paramName, paramName);
+ if (values != null && values.length > 1) {
+ List<Long> multiValues = extractLongList(request, searchCriteria,
+ paramName, userFriendlyParamName, paramName);
+ if (multiValues != null && multiValues.size() > 0) {
+ return multiValues.get(0);
+ } else {
+ return null;
+ }
+ } else {
+ Long value = restErrorUtil.parseLong(
+ request.getParameter(paramName), "Invalid value for "
+ + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ if (value != null) {
+ searchCriteria.getParamList().put(paramName, value);
+ }
+ return value;
+ }
+ }
+
+ public Integer extractInt(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName) {
+ Integer value = restErrorUtil.parseInt(request.getParameter(paramName),
+ "Invalid value for " + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ if (value != null) {
+ searchCriteria.getParamList().put(paramName, value);
+ }
+ return value;
+ }
+
+ /**
+ *
+ * @param request
+ * @param searchCriteria
+ * @param paramName
+ * @param userFriendlyParamName
+ * @param dateFormat
+ * @return
+ */
+ public Date extractDate(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName, String dateFormat) {
+ Date value = null;
+ if (dateFormat == null || dateFormat.isEmpty()) {
+ dateFormat = defaultDateFormat;
+ }
+ value = restErrorUtil.parseDate(request.getParameter(paramName),
+ "Invalid value for" + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName, dateFormat);
+ if (value != null) {
+ searchCriteria.getParamList().put(paramName, value);
+ }
+
+ return value;
+ }
+
+ public String extractString(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName, String regEx) {
+ String value = request.getParameter(paramName);
+ if (!stringUtil.isEmpty(value)) {
+ value = value.trim();
+ // TODO need to handle this in more generic way
+ // so as to take care of all possible special
+ // characters.
+ if(value.contains("%")){
+ value = value.replaceAll("%", "\\\\%");
+ }
+ if (!stringUtil.isEmpty(regEx)) {
+ restErrorUtil.validateString(value, regEx, "Invalid value for "
+ + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ }
+ searchCriteria.getParamList().put(paramName, value);
+ }
+ return value;
+ }
+
+ public List<Integer> extractEnum(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName, String listName, int maxValue) {
+
+ ArrayList<Integer> valueList = new ArrayList<Integer>();
+ String[] values = getParamMultiValues(request, paramName, listName);
+ for (int i = 0; values != null && i < values.length; i++) {
+ Integer value = restErrorUtil.parseInt(values[i],
+ "Invalid value for " + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+
+ restErrorUtil.validateMinMax(value, 0, maxValue,
+ "Invalid value for " + userFriendlyParamName, null,
+ paramName);
+ valueList.add(value);
+ }
+ if (valueList.size() > 0) {
+ searchCriteria.getParamList().put(listName, valueList);
+ }
+ return valueList;
+ }
+
+ /**
+ * @param request
+ * @param paramName
+ * @param listName
+ * @return
+ */
+ String[] getParamMultiValues(HttpServletRequest request, String paramName,
+ String listName) {
+ String[] values = request.getParameterValues(paramName);
+ if (values == null || values.length == 0) {
+ values = request.getParameterValues(paramName + "[]");
+ if (listName != null && (values == null || values.length == 0)) {
+ values = request.getParameterValues(listName);
+ if (values == null || values.length == 0) {
+ // Let's try after appending []
+ values = request.getParameterValues(listName + "[]");
+ }
+ }
+ }
+ return values;
+ }
+
+ public List<String> extractStringList(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName, String listName,
+ String[] validValues, String regEx) {
+ ArrayList<String> valueList = new ArrayList<String>();
+ String[] values = getParamMultiValues(request, paramName, listName);
+
+ for (int i = 0; values != null && i < values.length; i++) {
+ if (!stringUtil.isEmpty(regEx)) {
+ restErrorUtil.validateString(values[i], regEx,
+ "Invalid value for " + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ }
+ valueList.add(values[i]);
+ }
+ searchCriteria.getParamList().put(listName, valueList);
+ return valueList;
+ }
+
+ public List<Long> extractLongList(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName, String listName) {
+ ArrayList<Long> valueList = new ArrayList<Long>();
+ String[] values = getParamMultiValues(request, paramName, listName);
+
+ for (int i = 0; values != null && i < values.length; i++) {
+ Long value = restErrorUtil.parseLong(
+ values[i], "Invalid value for "
+ + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ valueList.add(value);
+ }
+ searchCriteria.getParamList().put(listName, valueList);
+ return valueList;
+ }
+
+ public void updateQueryPageSize(Query query, SearchCriteria searchCriteria) {
+ // Set max records
+ int pageSize = validatePageSize(searchCriteria.getMaxRows());
+
+ query.setMaxResults(pageSize);
+
+ // Set hint for max records
+ query.setHint("eclipselink.jdbc.max-rows", "" + pageSize);
+
+ }
+
+ public int validatePageSize(int inputPageSize) {
+ int pageSize = inputPageSize;
+
+ if (pageSize < 1) {
+ // Use default max Records
+ pageSize = configUtil.getDefaultMaxRows();
+ }
+ return pageSize;
+ }
+
+ /**
+ * @param searchCriteria
+ * @param sortFields
+ * @return
+ */
+ public String constructSortClause(SearchCriteria searchCriteria,
+ List<SortField> sortFields) {
+ String sortBy = searchCriteria.getSortBy();
+ String querySortBy = null;
+ if (!stringUtil.isEmpty(sortBy)) {
+ sortBy = sortBy.trim();
+ for (SortField sortField : sortFields) {
+ if (sortBy.equalsIgnoreCase(sortField.getParamName())) {
+ querySortBy = sortField.getFieldName();
+ // Override the sortBy using the normalized value
+ searchCriteria.setSortBy(sortField.getParamName());
+ break;
+ }
+ }
+ }
+
+ if (querySortBy == null) {
+ for (SortField sortField : sortFields) {
+ if (sortField.isDefault()) {
+ querySortBy = sortField.getFieldName();
+ // Override the sortBy using the default value
+ searchCriteria.setSortBy(sortField.getParamName());
+ searchCriteria.setSortType(sortField.getDefaultOrder()
+ .name());
+ break;
+ }
+ }
+ }
+
+ if (querySortBy != null) {
+ // Add sort type
+ String sortType = searchCriteria.getSortType();
+ String querySortType = "asc";
+ if (sortType != null) {
+ if (sortType.equalsIgnoreCase("asc")
+ || sortType.equalsIgnoreCase("desc")) {
+ querySortType = sortType;
+ } else {
+ logger.error("Invalid sortType. sortType=" + sortType);
+ }
+ }
+ // Override the sortType using the final value
+ if(querySortType!=null){
+ searchCriteria.setSortType(querySortType.toLowerCase());
+ }
+ String sortClause = " ORDER BY " + querySortBy + " "
+ + querySortType;
+
+ return sortClause;
+ }
+ return null;
+ }
+
+ protected StringBuilder buildWhereClause(SearchCriteria searchCriteria,
+ List<SearchField> searchFields) {
+ return buildWhereClause(searchCriteria, searchFields, false, false);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected StringBuilder buildWhereClause(SearchCriteria searchCriteria,
+ List<SearchField> searchFields, boolean isNativeQuery,
+ boolean excludeWhereKeyword) {
+
+ Map<String, Object> paramList = searchCriteria.getParamList();
+
+ StringBuilder whereClause = new StringBuilder(excludeWhereKeyword ? ""
+ : "WHERE 1 = 1 ");
+
+ List<String> joinTableList = new ArrayList<String>();
+
+ String addedByFieldName = isNativeQuery ? "added_by_id"
+ : "addedByUserId";
+
+ Number ownerId = searchCriteria.getOwnerId();
+ if (ownerId != null) {
+ whereClause.append(" and obj.").append(addedByFieldName)
+ .append(" = :ownerId");
+ }
+
+ // Let's handle search groups first
+ int groupCount = -1;
+ for (SearchGroup searchGroup : searchCriteria.getSearchGroups()) {
+ groupCount++;
+ whereClause.append(" and ").append(
+ searchGroup.getWhereClause("" + groupCount));
+// searchGroup.getJoinTableList(joinTableList, searchGroup);
+ }
+
+
+
+ for (SearchField searchField : searchFields) {
+ int startWhereLen = whereClause.length();
+
+ if (searchField.getFieldName() == null
+ && searchField.getCustomCondition() == null) { // this field
+ // is used
+ // only for
+ // binding!
+ continue;
+ }
+
+ Object paramValue = paramList.get(searchField.getClientFieldName());
+ boolean isListValue = false;
+ if (paramValue != null && paramValue instanceof Collection) {
+ isListValue = true;
+ }
+
+ if (searchCriteria.getNullParamList().contains(
+ searchField.getClientFieldName())) {
+ whereClause.append(" and ").append(searchField.getFieldName())
+ .append(" is null");
+ } else if (searchCriteria.getNotNullParamList().contains(
+ searchField.getClientFieldName())) {
+ whereClause.append(" and ").append(searchField.getFieldName())
+ .append(" is not null");
+
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST
+ || isListValue
+ && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
+ Collection<Number> intValueList = null;
+ if (paramValue != null
+ && (paramValue instanceof Integer || paramValue instanceof Long)) {
+ intValueList = new ArrayList<Number>();
+ intValueList.add((Number) paramValue);
+ } else {
+ intValueList = (Collection<Number>) paramValue;
+ }
+
+ if (intValueList != null && intValueList.size() > 0) {
+ if (searchField.getCustomCondition() == null) {
+ if (intValueList.size() <= minInListLength) {
+ whereClause.append(" and ");
+ if (intValueList.size() > 1) {
+ whereClause.append(" ( ");
+ }
+ for (int count = 0; count < intValueList.size(); count++) {
+ if (count > 0) {
+ whereClause.append(" or ");
+ }
+ whereClause
+ .append(searchField.getFieldName())
+ .append(" = :")
+ .append(searchField
+ .getClientFieldName()
+ + "_"
+ + count);
+ }
+
+ if (intValueList.size() > 1) {
+ whereClause.append(" ) ");
+ }
+
+ } else {
+ whereClause.append(" and ")
+ .append(searchField.getFieldName())
+ .append(" in ( :")
+ .append(searchField.getClientFieldName())
+ .append(")");
+ }
+ } else {
+ whereClause.append(" and ").append(
+ searchField.getCustomCondition());
+ }
+ }
+
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST) {
+ if (paramValue != null
+ && (((Collection) paramValue).size()) >=1) {
+ whereClause.append(" and ")
+ .append(searchField.getFieldName())
+ .append(" in ( :")
+ .append(searchField.getClientFieldName())
+ .append(")");
+ }
+ }
+ else if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
+ Number intFieldValue = (Number) paramList.get(searchField
+ .getClientFieldName());
+ if (intFieldValue != null) {
+ if (searchField.getCustomCondition() == null) {
+ whereClause.append(" and ")
+ .append(searchField.getFieldName())
+ .append("=:")
+ .append(searchField.getClientFieldName());
+ } else {
+ whereClause.append(" and ").append(
+ searchField.getCustomCondition());
+ }
+ }
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
+ String strFieldValue = (String) paramList.get(searchField
+ .getClientFieldName());
+ if (strFieldValue != null) {
+ if (searchField.getCustomCondition() == null) {
+ whereClause.append(" and ").append("LOWER(")
+ .append(searchField.getFieldName()).append(")");
+ if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) {
+ whereClause.append("= :").append(
+ searchField.getClientFieldName());
+ } else {
+ whereClause.append("like :").append(
+ searchField.getClientFieldName());
+ }
+ } else {
+ whereClause.append(" and ").append(
+ searchField.getCustomCondition());
+ }
+ }
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) {
+ Boolean boolFieldValue = (Boolean) paramList.get(searchField
+ .getClientFieldName());
+ if (boolFieldValue != null) {
+ if (searchField.getCustomCondition() == null) {
+ whereClause.append(" and ")
+ .append(searchField.getFieldName())
+ .append("=:")
+ .append(searchField.getClientFieldName());
+ } else {
+ whereClause.append(" and ").append(
+ searchField.getCustomCondition());
+ }
+ }
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) {
+ Date fieldValue = (Date) paramList.get(searchField
+ .getClientFieldName());
+ if (fieldValue != null) {
+ if (searchField.getCustomCondition() == null) {
+ whereClause.append(" and ").append(
+ searchField.getFieldName());
+ if (searchField.getSearchType().equals(
+ SearchField.SEARCH_TYPE.LESS_THAN)) {
+ whereClause.append("< :");
+ } else if (searchField.getSearchType().equals(
+ SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)) {
+ whereClause.append("<= :");
+ } else if (searchField.getSearchType().equals(
+ SearchField.SEARCH_TYPE.GREATER_THAN)) {
+ whereClause.append("> :");
+ } else if (searchField.getSearchType().equals(
+ SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)) {
+ whereClause.append(">= :");
+ }
+ whereClause.append(searchField.getClientFieldName());
+ } else {
+ whereClause.append(" and ").append(
+ searchField.getCustomCondition());
+ }
+ }
+
+ }
+
+ if (whereClause.length() > startWhereLen
+ && searchField.getJoinTables() != null) {
+ for (String table : searchField.getJoinTables()) {
+ if (!joinTableList.contains(table)) {
+ joinTableList.add(table);
+ }
+ }
+
+ whereClause.append(" and (")
+ .append(searchField.getJoinCriteria()).append(")");
+ }
+ } // for
+
+ for (String joinTable : joinTableList) {
+ whereClause.insert(0, ", " + joinTable + " ");
+ }
+
+ return whereClause;
+ }
+
+ protected void addOrderByClause(StringBuilder queryClause, String sortClause) {
+ if (sortClause != null) {
+ queryClause.append(sortClause);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void resolveQueryParams(Query query, SearchCriteria searchCriteria,
+ List<SearchField> searchFields) {
+
+ Map<String, Object> paramList = searchCriteria.getParamList();
+
+ Number ownerId = searchCriteria.getOwnerId();
+ if (ownerId != null) {
+ query.setParameter("ownerId", ownerId);
+ }
+
+ // Let's handle search groups first
+ int groupCount = -1;
+ for (SearchGroup searchGroup : searchCriteria.getSearchGroups()) {
+ groupCount++;
+ searchGroup.resolveValues(query, "" + groupCount);
+ }
+
+ for (SearchField searchField : searchFields) {
+ Object paramValue = paramList.get(searchField.getClientFieldName());
+ boolean isListValue = false;
+ if (paramValue != null && paramValue instanceof Collection) {
+ isListValue = true;
+ }
+
+ if (searchCriteria.getNullParamList().contains(
+ searchField.getClientFieldName())
+ || searchCriteria.getNotNullParamList().contains(
+ searchField.getClientFieldName())) {
+ // Already addressed while building where clause
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST
+ || isListValue
+ && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
+ Collection<Number> intValueList = null;
+ if (paramValue != null
+ && (paramValue instanceof Integer || paramValue instanceof Long)) {
+ intValueList = new ArrayList<Number>();
+ intValueList.add((Number) paramValue);
+ } else {
+ intValueList = (Collection<Number>) paramValue;
+ }
+
+ if (intValueList != null && intValueList.size() > 0
+ && intValueList.size() <= minInListLength) {
+ int count = -1;
+ for (Number value : intValueList) {
+ count++;
+ query.setParameter(searchField.getClientFieldName()
+ + "_" + count, value);
+
+ }
+
+ } else if (intValueList != null && intValueList.size() > 1) {
+ query.setParameter(searchField.getClientFieldName(),
+ intValueList);
+ }
+
+ }else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST) {
+ if (paramValue != null
+ && (((Collection) paramValue).size()) >=1) {
+ query.setParameter(searchField.getClientFieldName(),
+ paramValue);
+ }
+ }
+ else if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
+ Number intFieldValue = (Number) paramList.get(searchField
+ .getClientFieldName());
+ if (intFieldValue != null) {
+ query.setParameter(searchField.getClientFieldName(),
+ intFieldValue);
+ }
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
+ String strFieldValue = (String) paramList.get(searchField
+ .getClientFieldName());
+ if (strFieldValue != null) {
+ if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) {
+ query.setParameter(searchField.getClientFieldName(),
+ strFieldValue.trim().toLowerCase());
+ } else {
+ query.setParameter(searchField.getClientFieldName(),
+ "%" + strFieldValue.trim().toLowerCase() + "%");
+ }
+ }
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) {
+ Boolean boolFieldValue = (Boolean) paramList.get(searchField
+ .getClientFieldName());
+ if (boolFieldValue != null) {
+ query.setParameter(searchField.getClientFieldName(),
+ boolFieldValue);
+ }
+ } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) {
+ Date fieldValue = (Date) paramList.get(searchField
+ .getClientFieldName());
+ if (fieldValue != null) {
+ query.setParameter(searchField.getClientFieldName(),
+ fieldValue);
+ }
+ }
+
+ } // for
+ }
+
+ public Query createSearchQuery(EntityManager em, String queryStr, String sortClause,
+ SearchCriteria searchCriteria, List<SearchField> searchFields,
+ int objectClassType, boolean hasAttributes, boolean isCountQuery) {
+
+ // [1] Build where clause
+ StringBuilder queryClause = buildWhereClause(searchCriteria,
+ searchFields);
+
+ // [2] Add domain-object-security clause if needed
+ // if (objectClassType != -1
+ // && !ContextUtil.getCurrentUserSession().isUserAdmin()) {
+ // addDomainObjectSecuirtyClause(queryClause, hasAttributes);
+ // }
+
+ // [2] Add order by clause
+ addOrderByClause(queryClause, sortClause);
+
+ // [3] Create Query Object
+ Query query = em.createQuery(
+ queryStr + queryClause);
+
+ // [4] Resolve query parameters with values
+ resolveQueryParams(query, searchCriteria, searchFields);
+
+ // [5] Resolve domain-object-security parameters
+ // if (objectClassType != -1 &&
+ // !securityHandler.hasModeratorPermission()) {
+ // resolveDomainObjectSecuirtyParams(query, objectClassType);
+ // }
+
+ if (!isCountQuery) {
+ query.setFirstResult(searchCriteria.getStartIndex());
+ updateQueryPageSize(query, searchCriteria);
+ }
+
+ return query;
+ }
+
+ public Query createSearchQuery(EntityManager em, String queryStr, String sortClause,
+ SearchCriteria searchCriteria, List<SearchField> searchFields,
+ boolean isCountQuery) {
+ return createSearchQuery(em, queryStr, sortClause, searchCriteria,
+ searchFields, -1, false, isCountQuery);
+ }
+
+ public List<Integer> extractIntList(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName, String listName) {
+ ArrayList<Integer> valueList = new ArrayList<Integer>();
+ String[] values = getParamMultiValues(request, paramName, listName);
+
+ for (int i = 0; values != null && i < values.length; i++) {
+ Integer value = restErrorUtil.parseInt(
+ values[i], "Invalid value for "
+ + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ valueList.add(value);
+ }
+ searchCriteria.getParamList().put(listName, valueList);
+ return valueList;
+ }
+
+ public Boolean extractBoolean(HttpServletRequest request,
+ SearchCriteria searchCriteria, String paramName,
+ String userFriendlyParamName) {
+ Boolean value = restErrorUtil.parseBoolean(
+ request.getParameter(paramName), "Invalid value for "
+ + userFriendlyParamName,
+ MessageEnums.INVALID_INPUT_DATA, null, paramName);
+ if (value != null) {
+ searchCriteria.getParamList().put(paramName, value);
+ }
+ return value;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/SearchValue.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/SearchValue.java b/security-admin/src/main/java/org/apache/ranger/common/SearchValue.java
new file mode 100644
index 0000000..4a4d473
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/SearchValue.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+/**
+ *
+ *
+ */
+public class SearchValue {
+ static final Logger logger = Logger.getLogger(SearchValue.class);
+
+ SearchField searchField;
+ Object value = null;
+ List<?> valueList = null;
+ boolean isNull = false;
+
+ /**
+ * @return the value
+ */
+ public Object getValue() {
+ if (value != null) {
+ return value;
+ }
+ if (valueList.size() == 1) {
+ return valueList.get(0);
+ }
+ logger.error("getValue() called for null.", new Throwable());
+ return value;
+ }
+
+
+
+ /**
+ * @return the valueList
+ */
+ public List<?> getValueList() {
+ return valueList;
+ }
+
+ /**
+ * @return the searchField
+ */
+ public SearchField getSearchField() {
+ return searchField;
+ }
+
+
+
+
+ public boolean isList() {
+ return valueList != null && valueList.size() > 1;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/SortField.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/SortField.java b/security-admin/src/main/java/org/apache/ranger/common/SortField.java
new file mode 100644
index 0000000..7ffc188
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/SortField.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+/**
+ *
+ *
+ */
+public class SortField {
+ public enum SORT_ORDER {
+ ASC, DESC
+ };
+
+ String paramName;
+ String fieldName;
+ boolean isDefault = false;
+ SORT_ORDER defaultOrder = SORT_ORDER.ASC;
+
+ /**
+ * @param string
+ * @param string2
+ */
+ public SortField(String paramName, String fieldName) {
+ this.paramName = paramName;
+ this.fieldName = fieldName;
+ isDefault = false;
+ }
+
+ /**
+ * @param paramName
+ * @param fieldName
+ * @param isDefault
+ */
+ public SortField(String paramName, String fieldName, boolean isDefault,
+ SORT_ORDER defaultOrder) {
+ this.paramName = paramName;
+ this.fieldName = fieldName;
+ this.isDefault = isDefault;
+ this.defaultOrder = defaultOrder;
+ }
+
+ /**
+ * @return the paramName
+ */
+ public String getParamName() {
+ return paramName;
+ }
+
+
+
+ /**
+ * @return the fieldName
+ */
+ public String getFieldName() {
+ return fieldName;
+ }
+
+
+
+ /**
+ * @return the isDefault
+ */
+ public boolean isDefault() {
+ return isDefault;
+ }
+
+
+
+ /**
+ * @return the defaultOrder
+ */
+ public SORT_ORDER getDefaultOrder() {
+ return defaultOrder;
+ }
+
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/StringUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/StringUtil.java b/security-admin/src/main/java/org/apache/ranger/common/StringUtil.java
new file mode 100644
index 0000000..1eaff1a
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/StringUtil.java
@@ -0,0 +1,262 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+@Component
+public class StringUtil implements Serializable {
+ static final Logger logger = Logger.getLogger(StringUtil.class);
+
+ static final public int MIN_PASSWORD_LENGTH = 8;
+
+ static final public String VALIDATION_NAME = "[\\w\\ \\-\\']*";
+ static final public String VALIDATION_TEXT = "[a-zA-Z0-9\\ \"!@#$%^&*()-_=+;:'"|~`<>?/{}\\.\\,\\-\\?<>]*";
+ // Only for Student loginId
+ static final public String VALIDATION_LOGINID = "[a-z,A-Z][\\w\\-\\_]*[a-z,A-Z,0-9]";
+
+ static final public String VALIDATION_ALPHA = "[a-z,A-Z]*";
+ static final public String VALIDATION_IP_ADDRESS = "[\\d\\.\\%\\:]*";
+ static final public String WILDCARD_ASTERISK = "*";
+
+ static HashMap<String, Pattern> compiledRegEx = new HashMap<String, Pattern>();
+
+ String[] invalidNames = null;
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2102399594424760213L;
+
+ public StringUtil() {
+ // Default constructor
+ invalidNames = PropertiesUtil.getPropertyStringList("xa.names.invalid");
+ }
+
+ /**
+ * Checks if the string is null or empty string.
+ *
+ * @param str
+ * @return true if it is empty string or null
+ */
+ public boolean isEmpty(String str) {
+ if (str == null || str.trim().length() == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isEmptyOrWildcardAsterisk(String str) {
+ return isEmpty(str) || str.equals(WILDCARD_ASTERISK);
+ }
+
+ public boolean equals(String str1, String str2) {
+ if (str1 == str2) {
+ return true;
+ }
+
+ if (str1 == null || str2 == null) {
+ return false;
+ }
+
+ return str1.equals(str2);
+ }
+
+ public String toCamelCaseAllWords(String str) {
+ if (str == null) {
+ return null;
+ }
+ str = str.trim().toLowerCase();
+ StringBuffer result = new StringBuffer(str.length());
+ boolean makeUpper = true;
+ boolean lastCharSpace = true;
+ for (int c = 0; c < str.length(); c++) {
+ char ch = str.charAt(c);
+ if (lastCharSpace && ch == ' ') {
+ continue;
+ }
+
+ if (makeUpper) {
+ result.append(str.substring(c, c + 1).toUpperCase());
+ makeUpper = false;
+ } else {
+ result.append(ch);
+ }
+ if (ch == ' ') {
+ lastCharSpace = true;
+ makeUpper = true;
+ } else {
+ lastCharSpace = false;
+ }
+
+ }
+ return result.toString();
+ }
+
+ public boolean validatePassword(String password, String[] invalidValues) {
+ // For now let's make sure we have minimum 8 characters
+ if (password == null) {
+ return false;
+ }
+ password = password.trim();
+ if (password.length() < MIN_PASSWORD_LENGTH) {
+ return false;
+ }
+
+ boolean hasAlpha = false;
+ boolean hasNum = false;
+ for (int i = 0; i < password.length(); i++) {
+ char ch = password.charAt(i);
+
+ if (Character.isDigit(ch)) {
+ hasNum = true;
+ } else if (Character.isLetter(ch)) {
+ hasAlpha = true;
+ }
+ }
+
+ if (!hasAlpha || !hasNum) {
+ return false;
+ }
+
+ for (int i = 0; invalidValues != null && i < invalidValues.length; i++) {
+ if (password.equalsIgnoreCase(invalidValues[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean validateEmail(String emailAddress) {
+ if (emailAddress == null || emailAddress.trim().length() > 128) {
+ return false;
+ }
+ emailAddress = emailAddress.trim();
+ String expression = "^[\\w]([\\-\\.\\w])+[\\w]+@[\\w]+[\\w\\-]+[\\w]*\\.([\\w]+[\\w\\-]+[\\w]*(\\.[a-z][a-z|0-9]*)?)$";
+ return regExPatternMatch(expression, emailAddress);
+
+ }
+
+ public boolean regExPatternMatch(String expression, String inputStr) {
+ Pattern pattern = compiledRegEx.get(expression);
+ if (pattern == null) {
+ pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
+ compiledRegEx.put(expression, pattern);
+ }
+
+ Matcher matcher = pattern.matcher(inputStr);
+ return matcher.matches();
+ }
+
+ public boolean validateString(String regExStr, String str) {
+ try {
+ return regExPatternMatch(regExStr, str);
+ } catch (Throwable t) {
+ logger.info("Error validating string. str=" + str, t);
+ return false;
+ }
+ }
+
+ public String normalizeEmail(String email) {
+ // Make email address as lower case
+ if (email != null) {
+ return email.trim().toLowerCase();
+ }
+ return null;
+ }
+
+ public String[] split(String value) {
+ return split(value, ",");
+ }
+
+ public String[] split(String value, String delimiter) {
+ if (value != null) {
+ value = value.startsWith(delimiter) ? value.substring(1) : value;
+ String[] splitValues = value.split(delimiter);
+ String[] returnValues = new String[splitValues.length];
+ int c = -1;
+ for (int i = 0; i < splitValues.length; i++) {
+ String str = splitValues[i].trim();
+ if (str.length() > 0) {
+ c++;
+ returnValues[c] = str;
+ }
+ }
+ return returnValues;
+ } else {
+ return new String[0];
+ }
+ }
+
+ public static String trim(String str) {
+ return str != null ? str.trim() : null;
+ }
+
+ /**
+ * @param firstName
+ * @return
+ */
+ public boolean isValidName(String name) {
+ if (name == null || name.trim().length() < 1) {
+ return false;
+ }
+ for (String invalidName : invalidNames) {
+ if (name.toUpperCase().trim()
+ .startsWith(invalidName.toUpperCase().trim())) {
+ return false;
+ }
+ }
+ return validateString(VALIDATION_NAME, name);
+ }
+
+ /**
+ * Checks if the list is null or empty list.
+ *
+ * @param list
+ * @return true if it is empty list or null
+ */
+ public boolean isEmpty(List<?> list) {
+ if (list == null || list.size() == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns a valid user name from the passed string
+ * @param str
+ * @return
+ */
+ public String getValidUserName(String str) {
+ return str.indexOf("/") >= 0 ?
+ str.substring(0,str.indexOf("/"))
+ : str.indexOf("@") >= 0 ?
+ str.substring(0,str.indexOf("@"))
+ : str;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/TimedEventUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/TimedEventUtil.java b/security-admin/src/main/java/org/apache/ranger/common/TimedEventUtil.java
new file mode 100644
index 0000000..870b0d7
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/TimedEventUtil.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+@Component
+public class TimedEventUtil{
+
+ static final Logger logger = Logger.getLogger(TimedEventUtil.class);
+
+ public static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception {
+ timedTask(new Callable<Object>() {
+ @Override
+ public Object call() throws Exception {
+ runnable.run();
+ return null;
+ }
+ }, timeout, timeUnit);
+ }
+
+ public static <T> T timedTask(Callable<T> callableObj, long timeout,
+ TimeUnit timeUnit) throws Exception{
+
+ return callableObj.call();
+
+ /*
+ final ExecutorService executor = Executors.newSingleThreadExecutor();
+ final Future<T> future = executor.submit(callableObj);
+ executor.shutdownNow();
+
+ try {
+ return future.get(timeout, timeUnit);
+ } catch (TimeoutException | InterruptedException | ExecutionException e) {
+ if(logger.isDebugEnabled()){
+ logger.debug("Error executing task", e);
+ }
+ Throwable t = e.getCause();
+ if (t instanceof Error) {
+ throw (Error) t;
+ } else if (t instanceof Exception) {
+ throw (Exception) e;
+ } else {
+ throw new IllegalStateException(t);
+ }
+ }
+ */
+
+ }
+
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java b/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java
new file mode 100644
index 0000000..b009193
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.apache.ranger.common;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.ranger.entity.XXAuthSession;
+import org.apache.ranger.entity.XXPortalUser;
+
+public class UserSessionBase implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ XXPortalUser xXPortalUser;
+ XXAuthSession xXAuthSession;
+ private boolean userAdmin;
+ private int authProvider = XAConstants.USER_APP;
+ private List<String> userRoleList = new ArrayList<String>();
+ int clientTimeOffsetInMinute = 0;
+ public Long getUserId() {
+ if (xXPortalUser != null) {
+ return xXPortalUser.getId();
+ }
+ return null;
+ }
+
+ public String getLoginId() {
+ if (xXPortalUser != null) {
+ return xXPortalUser.getLoginId();
+ }
+ return null;
+ }
+
+ public Long getSessionId() {
+ if (xXAuthSession != null) {
+ return xXAuthSession.getId();
+ }
+ return null;
+ }
+
+
+
+ public boolean isUserAdmin() {
+ return userAdmin;
+ }
+
+
+
+
+ public void setUserAdmin(boolean userAdmin) {
+ this.userAdmin = userAdmin;
+ }
+
+ public XXPortalUser getXXPortalUser() {
+ return xXPortalUser;
+ }
+
+ public String getUserName() {
+ if (xXPortalUser != null) {
+ return xXPortalUser.getFirstName() + " " + xXPortalUser.getLastName();
+ }
+ return null;
+ }
+
+ public void setXXAuthSession(XXAuthSession gjAuthSession) {
+ this.xXAuthSession = gjAuthSession;
+ }
+
+ public void setXXPortalUser(XXPortalUser gjUser) {
+ this.xXPortalUser = gjUser;
+ }
+
+ public void setAuthProvider(int userSource) {
+ this.authProvider = userSource;
+ }
+
+ public void setUserRoleList(List<String> strRoleList) {
+ this.userRoleList = strRoleList;
+ }
+
+ public int getAuthProvider() {
+ return this.authProvider;
+ }
+
+ public int getClientTimeOffsetInMinute() {
+ return clientTimeOffsetInMinute;
+ }
+
+ public void setClientTimeOffsetInMinute(int clientTimeOffsetInMinute) {
+ this.clientTimeOffsetInMinute = clientTimeOffsetInMinute;
+ }
+
+}